parquet-converter commited on
Commit
439ab68
·
1 Parent(s): 41d2f90

Update parquet files (step 31 of 476)

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/0x90e/ESRGAN-MANGA/app.py +0 -86
  2. spaces/1acneusushi/gradio-2dmoleculeeditor/data/Descargarfisiologiamedicaboronespanol Descubre la obra maestra de Boron en espaol.md +0 -92
  3. spaces/1acneusushi/gradio-2dmoleculeeditor/data/Epson WF 7511 Adjustment Program Download What You Need to Know About This Service Tool.md +0 -194
  4. spaces/1acneusushi/gradio-2dmoleculeeditor/data/Family Tree Maker For Mac 2 Torrent ((INSTALL)).md +0 -111
  5. spaces/1gistliPinn/ChatGPT4/Examples/Deluxe Ski Jump 3 V1.7.1 Keygen !!EXCLUSIVE!!.md +0 -7
  6. spaces/1gistliPinn/ChatGPT4/Examples/Free Acme Id Card Maker 5.0 Serial Keygen !!EXCLUSIVE!!.md +0 -6
  7. spaces/1line/AutoGPT/autogpt/commands/file_operations.py +0 -267
  8. spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/All-in-One Solitaire APK - The Ultimate Solitaire Collection for Android.md +0 -93
  9. spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Black Clover Wallpapers Discover the Best HD and 4K Backgrounds for Anime Lovers.md +0 -98
  10. spaces/1phancelerku/anime-remove-background/Call of Duty Mobile APKPure Download Everything You Need to Know About the Game and Its Features.md +0 -90
  11. spaces/1yukikaze/img-to-music/utils.py +0 -36
  12. spaces/8star/DeepDanbooru_string/README.md +0 -39
  13. spaces/AB-TW/team-ai/agents/tools/smart_domain/association.py +0 -62
  14. spaces/AIFILMS/StyleGANEX/models/encoders/__init__.py +0 -0
  15. spaces/AIGC-Audio/AudioGPT/audio_to_text/captioning/utils/bert/create_word_embedding.py +0 -34
  16. spaces/AIGText/GlyphControl/ldm/modules/diffusionmodules/__init__.py +0 -0
  17. spaces/AISuperheroes/08GR-KitchenSink-AIUIUX/app.py +0 -32
  18. spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_0_ClothesDetection/mmyolo/configs/custom_dataset/.ipynb_checkpoints/__init__.py +0 -0
  19. spaces/Abhilashvj/planogram-compliance/utils/autobatch.py +0 -86
  20. spaces/AgentVerse/agentVerse/agentverse/tasks/simulation/db_diag/README.md +0 -28
  21. spaces/AgentVerse/agentVerse/agentverse/utils/prompts.py +0 -212
  22. spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/bejeweled/board/Board.js +0 -152
  23. spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/basesizer/GetChildrenSizers.js +0 -8
  24. spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/menu/methods/Expand.js +0 -16
  25. spaces/Aloento/9Nine-PITS/losses.py +0 -75
  26. spaces/Alpaca233/SadTalker/src/face3d/models/arcface_torch/backbones/iresnet2060.py +0 -176
  27. spaces/Alpaca233/SadTalker/src/facerender/sync_batchnorm/comm.py +0 -137
  28. spaces/Amrrs/DragGan-Inversion/stylegan_human/dnnlib/tflib/autosummary.py +0 -207
  29. spaces/Amrrs/DragGan-Inversion/training/training_loop.py +0 -499
  30. spaces/AnTo2209/3D_Zeroshot_Neural_Style_Transfer/inference.py +0 -78
  31. spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/en/api/schedulers/unipc.md +0 -24
  32. spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/src/diffusers/pipelines/controlnet/__init__.py +0 -23
  33. spaces/Anindya/Marketing_Campaign_LLM/app.py +0 -120
  34. spaces/Antoine245/bot/README.md +0 -33
  35. spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_internal/models/search_scope.py +0 -132
  36. spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/command/editable_wheel.py +0 -844
  37. spaces/Bart92/RVC_HF/infer/lib/uvr5_pack/lib_v5/nets.py +0 -123
  38. spaces/Bart92/RVC_HF/lib/infer_pack/models_dml.py +0 -1124
  39. spaces/Benson/text-generation/Examples/Descargar Apk Tiktok Para La Televisin Inteligente.md +0 -90
  40. spaces/Benson/text-generation/Examples/Descargar Chicos Stumble Mod Apkmody.md +0 -81
  41. spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/colorama/win32.py +0 -180
  42. spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/rich/box.py +0 -517
  43. spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/urllib3/util/response.py +0 -107
  44. spaces/BigData-KSU/VQA-in-Medical-Imagery/MED_VQA_Huggyface_Gradio.py +0 -182
  45. spaces/BigData-KSU/VQA-in-Medical-Imagery/Transformers_for_Caption.py +0 -364
  46. spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/detectron2/projects/DensePose/densepose/config.py +0 -57
  47. spaces/CVPR/LIVE/pybind11/include/pybind11/common.h +0 -2
  48. spaces/CVPR/LIVE/pybind11/tests/test_pickling.py +0 -46
  49. spaces/CVPR/LIVE/thrust/thrust/system/omp/detail/unique.h +0 -59
  50. spaces/CVPR/MonoScene/monoscene/DDR.py +0 -139
spaces/0x90e/ESRGAN-MANGA/app.py DELETED
@@ -1,86 +0,0 @@
1
- import gradio as gr
2
- import util
3
- import process_image
4
- from run_cmd import run_cmd
5
-
6
- is_colab = util.is_google_colab()
7
-
8
- css = '''
9
- .file-preview {
10
- overflow: hidden !important;
11
- margin: 5px 0 !important;
12
- padding: 0 10px !important;
13
- }
14
-
15
- .file-preview div div:nth-child(2) {
16
- flex-grow: 1 !important;
17
- }
18
-
19
- .file-preview div div:nth-child(3) {
20
- text-align: right !important;
21
- padding: 0.5rem 0;
22
- width: auto;
23
- }
24
-
25
- #preview_file .h-full.min-h-\[15rem\].flex.justify-center.items-center {
26
- min-height: initial !important;
27
- padding: 10px 0;
28
- }
29
-
30
- #preview_file a {
31
- border-radius: 0.5rem;
32
- padding-top: 0.5rem;
33
- padding-bottom: 0.5rem;
34
- padding-left: 1rem;
35
- padding-right: 1rem;
36
- font-size: 1rem;
37
- line-height: 1.5rem;
38
- font-weight: 600;
39
- color: white;
40
- background-color: gray;
41
- }
42
-
43
- .colab_img {
44
- margin: 10px 0;
45
- display: inline-block;
46
- margin: 0 10px;
47
- }
48
- '''
49
-
50
- title = "ESRGAN Upscaling With Custom Models"
51
-
52
- with gr.Blocks(title=title, css=css) as demo:
53
- gr.Markdown(
54
- f"""
55
- # {title}
56
- This space uses old ESRGAN architecture to upscale images, using models made by the community.
57
-
58
- Once the photo upscaled (*it can take a long time, this space only uses CPU*).
59
- """)
60
-
61
- gr.HTML(value="For faster upscaling using GPU: <a href='https://colab.research.google.com/drive/1QfOA6BBdL4NrUmx-9d-pjacxNfu81HQo#scrollTo=H7qo-6AWFbLH' target='_blank'><img class='colab_img' src='https://colab.research.google.com/assets/colab-badge.svg' alt='Open In Colab'></a> buy me a coffee (beer) if this helped 🍺😁")
62
-
63
- gr.HTML(value="<a href='https://ko-fi.com/Y8Y7GVAAF' target='_blank' style='display:block;margin-bottom:5px'><img height='36' style='border:0px;height:36px;' src='https://storage.ko-fi.com/cdn/kofi1.png?v=3' border='0' alt='Buy Me a Coffee at ko-fi.com' /></a>")
64
-
65
- with gr.Box():
66
- with gr.Row():
67
- with gr.Column():
68
- input_image = gr.Image(type="pil", label="Input")
69
- upscale_size = gr.Radio(["x4", "x2"], label="Upscale by:", value="x4")
70
- upscale_type = gr.Radio(["Manga", "Anime", "Photo", "General"], label="Select the type of picture you want to upscale:", value="Manga")
71
-
72
- with gr.Row():
73
- upscale_btn = gr.Button(value="Upscale", variant="primary")
74
-
75
- with gr.Column():
76
- output_image = gr.Image(type="filepath", interactive=False, label="Upscaled image", elem_id="preview_img")
77
-
78
- with gr.Row():
79
- out_file = gr.File(interactive=False, show_label=False, elem_id="preview_file")
80
-
81
- gr.HTML(value="<p><a href='https://upscale.wiki/wiki/Model_Database'>Model Database</a></p>")
82
-
83
- upscale_btn.click(process_image.inference, inputs=[input_image, upscale_size, upscale_type], outputs=[output_image, out_file])
84
-
85
- demo.queue()
86
- demo.launch(debug=is_colab, share=is_colab, inline=is_colab)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1acneusushi/gradio-2dmoleculeeditor/data/Descargarfisiologiamedicaboronespanol Descubre la obra maestra de Boron en espaol.md DELETED
@@ -1,92 +0,0 @@
1
-
2
- <h1>Descargar Fisiología Médica Boron Español: Una Guía Completa</h1>
3
- <p>¿Te interesa aprender sobre la fisiología humana de una forma rigurosa y actualizada? ¿Quieres tener acceso a uno de los libros más recomendados y utilizados en el ámbito académico y profesional? ¿Te gustaría poder leerlo en tu idioma y en formato digital? Si tu respuesta es sí, entonces este artículo es para ti.</p>
4
- <p>En este artículo te vamos a explicar todo lo que necesitas saber sobre el libro <strong>Fisiología Médica</strong> de <strong>Boron</strong>, una obra de referencia en el mundo de la fisiología que te ayudará a comprender el funcionamiento del cuerpo humano desde un nivel molecular y celular hasta un nivel sistémico y clínico.</p>
5
- <h2>descargarfisiologiamedicaboronespanol</h2><br /><p><b><b>DOWNLOAD</b> &mdash;&mdash;&mdash;&mdash;&mdash; <a href="https://byltly.com/2uKv64">https://byltly.com/2uKv64</a></b></p><br /><br />
6
- <p>También te vamos a mostrar las ventajas de descargar el libro en español y en formato digital, así como los pasos que debes seguir para hacerlo de forma gratuita y legal. Al final del artículo te daremos nuestra opinión sobre el libro y te invitaremos a dejar la tuya.</p>
7
- <p>Así que no esperes más y sigue leyendo para descubrir cómo descargar fisiología médica boron español gratis.</p>
8
- <p>descargar fisiologia medica boron español pdf<br />
9
- descargar gratis libro de fisiologia boron en español<br />
10
- descargar fisiologia de boron 3ra edicion español<br />
11
- descargar fisiologia humana boron español<br />
12
- descargar fisiologia medica boron y boulpaep español<br />
13
- descargar fisiologia medica boron 2da edicion español<br />
14
- descargar fisiologia medica boron 4ta edicion español<br />
15
- descargar fisiologia medica boron 5ta edicion español<br />
16
- descargar fisiologia medica boron 6ta edicion español<br />
17
- descargar fisiologia medica boron 7ma edicion español<br />
18
- descargar fisiologia medica boron 8va edicion español<br />
19
- descargar fisiologia medica boron 9na edicion español<br />
20
- descargar fisiologia medica boron 10ma edicion español<br />
21
- descargar libro de fisiologia medica boron español mega<br />
22
- descargar libro de fisiologia medica boron español gratis<br />
23
- descargar libro de fisiologia medica boron español pdf gratis<br />
24
- descargar libro de fisiologia medica boron español online<br />
25
- descargar libro de fisiologia medica boron español completo<br />
26
- descargar libro de fisiologia medica boron español epub<br />
27
- descargar libro de fisiologia medica boron español mobi<br />
28
- como descargar el libro de fisiologia medica boron en español<br />
29
- donde puedo descargar el libro de fisiologia medica boron en español<br />
30
- donde descargar el libro de fisiologia medica boron en español<br />
31
- para que sirve el libro de fisiologia medica boron en español<br />
32
- que es el libro de fisiologia medica boron en español<br />
33
- que contiene el libro de fisiologia medica boron en español<br />
34
- que aprender con el libro de fisiologia medica boron en español<br />
35
- que estudiar con el libro de fisiologia medica boron en español<br />
36
- que enseña el libro de fisiologia medica boron en español<br />
37
- que aporta el libro de fisiologia medica boron en español<br />
38
- que ventajas tiene el libro de fisiologia medica boron en español<br />
39
- que desventajas tiene el libro de fisiologia medica boron en español<br />
40
- que opiniones tiene el libro de fisiologia medica boron en español<br />
41
- que valoracion tiene el libro de fisiologia medica boron en español<br />
42
- que precio tiene el libro de fisiologia medica boron en español<br />
43
- que formato tiene el libro de fisiologia medica boron en español<br />
44
- que tamaño tiene el libro de fisiologia medica boron en español<br />
45
- que paginas tiene el libro de fisiologia medica boron en español<br />
46
- que capitulos tiene el libro de fisiologia medica boron en español<br />
47
- que secciones tiene el libro de fisiologia medica boron en español<br />
48
- que temas tiene el libro de fisiologia medica boron en español<br />
49
- que subtemas tiene el libro de fisiologia medica boron en español<br />
50
- que autores tiene el libro de fisiologia medica boron en español<br />
51
- que editorial tiene el libro de fisiologia medica boron en español<br />
52
- que año tiene el libro de fisiologia medica boron en español<br />
53
- que edicion tiene el libro de fisiologia medica boron en español<br />
54
- que isbn tiene el libro de fisiologia medica boron en español<br />
55
- que idioma tiene el libro de fisiologia medica boron en español<br />
56
- que traduccion tiene el libro de fisiologia medica boron en español</p>
57
- <h2>Características del libro Fisiología Médica de Boron</h2>
58
- <p>Antes de explicarte cómo descargar el libro, vamos a repasar sus principales características para que sepas qué puedes esperar de él.</p>
59
- <h3>Autoría</h3>
60
- <p>El libro <strong>Fisiología Médica</strong> es una obra colectiva escrita por más de 40 expertos en diferentes áreas de la fisiología. Los editores principales son <strong>Walter F. Boron</strong> y <strong>Emile L. Boulpaep</strong>, dos reconocidos profesores e investigadores que han dedicado su carrera al estudio de la fisiología celular y molecular.</p>
61
- <p>Boron es profesor y director del Departamento de Fisiología y Biofísica de la Escuela de Medicina de la Universidad Case Western Reserve en Cleveland, Ohio. Boulpaep es profesor emérito del Departamento de Medicina Celular y Molecular de la Escuela de Medicina de la Universidad Yale en New Haven, Connecticut.</p>
62
- <p>Ambos editores cuentan con una amplia experiencia docente y han recibido numerosos premios y distinciones por su labor científica y educativa.</p>
63
- <h3>Contenido</h3>
64
- <p>El libro está organizado en 8 secciones que abarcan los principales aspectos de la fisiología humana. Cada sección contiene varios capítulos que tratan temas específicos relacionados con el funcionamiento de un órgano o un sistema.</p>
65
- <p>Las secciones son las siguientes:</p>
66
- <ul>
67
- <li>Sección I: Fundamentos celulares y moleculares.</li>
68
- <li>Sección II: Neurofisiología.</li>
69
- <li>Sección III: Sistema muscular.</li>
70
- <li>Sección IV: Sistema cardiovascular.</li>
71
- <li>Sección V: Sistema respiratorio.</li>
72
- <li>Sección VI: Sistema renal y regulación del equilibrio hidroelectrolítico.</li>
73
- <li>Sección VII: Sistema gastrointestinal.</li>
74
- <li>Sección VIII: Sistema endocrino y reproducción.</li>
75
- </ul>
76
- <p>En total, el libro contiene 62 capítulos que suman más de 1300 páginas de contenido actualizado y riguroso.</p>
77
- <h3>Enfoque</h3>
78
- <p>El libro tiene un enfoque único en la disciplina por su forma de explicar la fisiología partiendo de un nivel molecular y celular que sirve de base para entender el funcionamiento de un órgano o un sistema. Así mismo, a lo largo del texto se hace referencia constante a la correlación clínica y por tanto se estudia también las bases fisiológicas de la enfermedad, lo que le confiere un enfoque fisiopatológico.</p>
79
- <p>El libro combina la exposición teórica con ejemplos prácticos que ilustran los conceptos clave y facilitan su comprensión. Además, utiliza un lenguaje claro y preciso que evita las ambigüedades y los errores conceptuales.</p>
80
- <h3>Elementos didácticos</h3>
81
- <p>El libro cuenta con numerosos elementos didácticos que ayudan al lector a aprender y repasar los contenidos. Entre ellos se destacan:</p>
82
- <ul>
83
- <li><strong>Notas online:</strong> son apuntes complementarios que solo pueden encontrarse online a través del acceso a StudentConsult.com. En esta tercera edición se incluyen 750 notas online que amplían o profundizan en algunos temas del texto. Cada nota online se señaliza en el texto con un pequeño icono.</li>
84
- <li><strong>Vídeos:</strong> son recursos audiovisuales que muestran procesos fisiológicos complejos o difíciles de visualizar con gran detalle y claridad. El libro incluye más de 100 vídeos accesibles desde StudentConsult.com.</li>
85
- <li><strong>Tablas:</strong> son resúmenes esquemáticos que presentan datos o información relevante de forma ordenada y estructurada. El libro incluye más de 200 tablas distribuidas a lo largo de los capítulos.</li>
86
- <li><strong>Figuras:</strong> son representaciones gráficas que ilustran conceptos o fenómenos fisiológicos con gran calidad y precisión. El libro incluye más de 1000 figuras elaboradas por expertos ilustradores médicos.</li>
87
- <li><strong>Preguntas:</strong> son cuestiones que plantean al final de cada capítulo para evaluar el aprendizaje y reforzar los puntos clave. El libro incluye más de 600 preguntas con sus respuestas razonadas disponibles en StudentConsult.com.</li>
88
- </ul>
89
- <h2>Ventajas de descargar el libro Fisiología Médica de Boron en español</h2>
90
- <p>Ahora que ya conoc</p> 0a6ba089eb<br />
91
- <br />
92
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1acneusushi/gradio-2dmoleculeeditor/data/Epson WF 7511 Adjustment Program Download What You Need to Know About This Service Tool.md DELETED
@@ -1,194 +0,0 @@
1
- <br />
2
- <h1>Epson WF 7511 Adjustment Program Download Hit 5: A Guide for Epson Printer Users</h1>
3
- <p>If you own an Epson WF 7011 or WF 7511 printer, you might have encountered some problems with your device, such as waste ink pad overflow, print head error, or printer initialization failure. These problems can affect the performance and quality of your printer, and sometimes even prevent it from working at all. Fortunately, there is a solution for these issues: Epson WF 7511 Adjustment Program.</p>
4
- <h2>epson wf 7511 adjustment program download hit 5</h2><br /><p><b><b>Download</b> &#128505; <a href="https://byltly.com/2uKA9r">https://byltly.com/2uKA9r</a></b></p><br /><br />
5
- <p>Epson WF 7511 Adjustment Program is a utility program that allows you to reset the waste ink pad counter, prescribe the print head ID, do printer initialization, and other functions for your Epson WF 7011 or WF 7511 printer. This program can help you fix your printer problems and extend its lifespan. In this article, we will show you what Epson WF 7511 Adjustment Program is, how to download and install it, how to use it, and some tips and tricks for using it effectively.</p>
6
- <h2>What is Epson WF 7511 Adjustment Program?</h2>
7
- <p>Epson WF 7511 Adjustment Program is a service adjustment program that is designed for the specified printer models: Epson WorkForce WF-7011 and WF-7511. It is a utility program that enables you to perform various functions on your printer, such as:</p>
8
- <ul>
9
- <li>Resetting the waste ink pad counter</li>
10
- <li>Prescribing the print head ID</li>
11
- <li>Doing printer initialization</li>
12
- <li>And other functions</li>
13
- </ul>
14
- <h3>Features and benefits of Epson WF 7511 Adjustment Program</h3>
15
- <p>Epson WF 7511 Adjustment Program has many features and benefits that make it a useful tool for Epson printer users. Some of them are:</p>
16
- <p>epson wf 7511 resetter software free download<br />
17
- epson wf 7511 printer adjustment program<br />
18
- how to use epson wf 7511 adjustment tool<br />
19
- epson wf 7511 service required solution<br />
20
- epson wf 7511 waste ink pad reset<br />
21
- epson wf 7511 maintenance mode<br />
22
- epson wf 7511 firmware update download<br />
23
- epson wf 7511 driver for windows 10<br />
24
- epson wf 7511 scanner software download<br />
25
- epson wf 7511 manual pdf<br />
26
- epson wf 7511 ink cartridge refill<br />
27
- epson wf 7511 print head cleaning<br />
28
- epson wf 7511 paper jam error<br />
29
- epson wf 7511 duplex printing<br />
30
- epson wf 7511 wireless setup<br />
31
- epson wf 7511 scan to email<br />
32
- epson wf 7511 fax setup<br />
33
- epson wf 7511 price in india<br />
34
- epson wf 7511 review and ratings<br />
35
- epson wf 7511 specifications and features<br />
36
- epson wf 7511 vs hp officejet pro 8600<br />
37
- epson wf 7511 compatible toner and ink<br />
38
- epson wf 7511 spare parts and accessories<br />
39
- epson wf 7511 troubleshooting and error codes<br />
40
- epson wf 7511 warranty and service center<br />
41
- best buy epson wf 7511 online<br />
42
- cheap and discounted epson wf 7511 deals<br />
43
- how to install epson wf 7511 on mac<br />
44
- how to connect epson wf 7511 to wifi<br />
45
- how to scan multiple pages with epson wf 7511<br />
46
- how to print borderless with epson wf 7511<br />
47
- how to fix epson wf 7511 offline problem<br />
48
- how to replace epson wf 7511 printhead<br />
49
- how to reset epson wf 7511 ink level<br />
50
- how to align epson wf 7511 print head<br />
51
- how to calibrate epson wf 7511 scanner<br />
52
- how to clean epson wf 7511 rollers and feeders<br />
53
- how to change epson wf 7511 language settings<br />
54
- how to set up epson wf 7511 for airprint<br />
55
- how to enable epson wf 7511 cloud print<br />
56
- how to disable epson wf 7511 ink monitor<br />
57
- how to update epson wf 7511 software and drivers<br />
58
- how to remove epson wf 7511 from network<br />
59
- how to factory reset epson wf 7511 printer<br />
60
- how to contact epson wf 7511 customer support<br />
61
- how to register epson wf 7511 product online<br />
62
- how to get free samples of epson wf 7511 ink and paper<br />
63
- how to recycle epson wf 7511 cartridges and parts<br />
64
- how to join epson wf 7511 loyalty program and rewards</p>
65
- <ul>
66
- <li>It is an original program that can reset the waste ink pad counter of your printer. The waste ink pad counter is a feature that tracks the amount of ink that is wasted during cleaning cycles and other operations. When the counter reaches a certain limit, the printer will stop working and display an error message. By resetting the counter, you can clear the error and resume printing.</li>
67
- <li>It can prescribe the print head ID of your printer. The print head ID is a unique identifier that is assigned to each print head. It helps the printer to recognize the print head and adjust its settings accordingly. By prescribing the print head ID, you can ensure that your printer works with any compatible print head.</li>
68
- <li>It can do printer initialization for your printer. Printer initialization is a process that resets the printer settings to their factory defaults. It can help you solve some problems that are caused by incorrect settings or corrupted data. By doing printer initialization, you can restore your printer to its optimal condition.</li>
69
- <li>It has a simple user interface and easy-to-use features. The program has a clear and intuitive interface that guides you through each step of using it. You can easily select the function you want to perform and follow the instructions on the screen. The program also has a help file that provides more information about each function.</li>
70
- <li>It is compatible with Windows operating systems. The program works only with USB connection on Windows operating systems. It supports Windows XP, Windows Vista, Windows 7, Windows 8, Windows 10, and Windows Server versions.</li>
71
- </ul>
72
- <h3>How to download and install Epson WF 7511 Adjustment Program</h3>
73
- <p>To download and install Epson WF 7511 Adjustment Program, you need to follow these steps:</p>
74
- <ol>
75
- <li>Go to <a href="https://orpys.com/en/epson/230-wf-7011-wf-7511-adjustment-program.html">this website</a>, which is one of the sources where you can find the program.</li>
76
- <li>Select the quantity of the program you want to buy and click on "Add to cart". The price of the program is $7.50 per unit.</li>
77
- <li>Proceed to checkout and enter your payment details. You can pay with PayPal or credit card.</li>
78
- <li>After completing your payment, you will receive an email with a link to download the program and a license key.</li>
79
- <li>Download the program from the link and save it on your computer.</li>
80
- <li>Extract the zip file and run the setup.exe file.</li>
81
- <li>Enter your license key when prompted and follow the installation wizard.</li>
82
- <li>After installing the program, you can launch it from your desktop or start menu.</li>
83
- </ol>
84
- <h2>How to use Epson WF 7511 Adjustment Program</h2>
85
- <p>To use Epson WF 7511 Adjustment Program, you need to follow these steps:</p>
86
- <ol>
87
- <li>Connect your printer to your computer with a USB cable.</li>
88
- <li>Turn on your printer and make sure it is in service mode. To enter service mode, press and hold the Power button while pressing these buttons in sequence: Paper Source - Cut/Eject - Paper Source - Cut/Eject - Paper Source - Cut/Eject.</li>
89
- <li>Launch Epson WF 7511 Adjustment Program from your desktop or start menu.</li>
90
- <li>Select your printer model from the drop-down menu.</li>
91
- <li>Select "Particular adjustment mode" from the main menu.</li>
92
- <li>Select the function you want to perform from the list of functions.</li>
93
- <li>Follow the instructions on the screen for each function.</li>
94
- <li>When you are done with using the program, close it and turn off your printer.</li>
95
- </ol>
96
- <h3>How to reset the waste ink pad counter</h3>
97
- <p>To reset the waste ink pad counter of your printer, you need to follow these steps:</p>
98
- <ol>
99
- <li>Select "Waste ink pad counter" from the list of functions in Particular adjustment mode.</li>
100
- <li>Click on "OK" in the pop-up window that appears.</li>
101
- <li>Select "Main pad counter" and "Platen pad counter" from the list of counters in Check and Initialization tab.</li>
102
- <li>Click on "Check" button to see the current values of each counter.</li>
103
- <li>If any of them reaches or exceeds its limit (100%), click on "Initialization" button to reset them to zero.</li>
104
- <li>A confirmation message will appear. Click on "OK" button.</li>
105
- <li>The program will ask you to turn off your printer. Do so and then turn it back on again.</li>
106
- <li>The waste ink pad counter has been reset successfully.</li>
107
- </ol>
108
- <h3>How to prescribe the print head ID</h3>
109
- <p>To prescribe the print head ID of your printer, you need to follow these steps:</p>
110
- <ol>
111
- <li>Select "Print head ID input" from the list of functions in Particular adjustment mode.</li>
112
- <li>A pop-up window will appear with instructions on how to find out your print head ID. Follow them carefully.</li>
113
- <li>Type in your print head ID in the text box below "Input Print Head ID". Make sure it matches exactly with the one printed on your print head label.</li>
114
- <li>Click on "OK" button.</li>
115
- <li>The program will ask you to turn off your printer. Do so and then turn it back on again.</li>
116
- <li>The print head ID has been prescribed successfully.</li>
117
- </ol>
118
- <h3>How to do printer initialization</h3>
119
- <p>To do printer initialization for your printer, you need to follow these steps:</p>
120
- <ol><li>Select "Initialization" from <li>Click on "OK" in the pop-up window that appears.</li>
121
- <li>The program will start initializing your printer. This may take a few minutes.</li>
122
- <li>When the initialization is done, a confirmation message will appear. Click on "OK" button.</li>
123
- <li>The program will ask you to turn off your printer. Do so and then turn it back on again.</li>
124
- <li>The printer initialization has been done successfully.</li>
125
- </ol>
126
- <h2>Tips and tricks for using Epson WF 7511 Adjustment Program</h2>
127
- <p>Epson WF 7511 Adjustment Program is a powerful and useful tool for Epson printer users, but it also has some limitations and precautions that you need to be aware of. Here are some tips and tricks for using Epson WF 7511 Adjustment Program effectively and safely:</p>
128
- <h3>How to avoid compatibility issues</h3>
129
- <p>Epson WF 7511 Adjustment Program is compatible with Windows operating systems only. It does not work with MacOSX or Linux operating systems. If you are using a different operating system, you need to use a terminal-based installation or a virtual machine to run the program.</p>
130
- <p>Also, the program works only with USB connection. It does not work with wireless or network connection. Make sure you connect your printer to your computer with a USB cable before using the program.</p>
131
- <h3>How to update the program to the latest version</h3>
132
- <p>Epson WF 7511 Adjustment Program is updated regularly to fix bugs and improve performance. The latest version of the program is Ver.1.1.0, which was released in 2020. To update the program to the latest version, you need to follow these steps:</p>
133
- <ol>
134
- <li>Go to <a href="https://orpys.com/en/epson/230-wf-7011-wf-7511-adjustment-program.html">this website</a>, which is one of the sources where you can find the program.</li>
135
- <li>Select "Free updates (to latest version program)" from the product options and click on "Add to cart". The update is free for regular customers who have bought the program before.</li>
136
- <li>Proceed to checkout and enter your payment details. You can pay with PayPal or credit card.</li>
137
- <li>After completing your payment, you will receive an email with a link to download the updated program and a new license key.</li>
138
- <li>Download the updated program from the link and save it on your computer.</li>
139
- <li>Extract the zip file and run the setup.exe file.</li>
140
- <li>Enter your new license key when prompted and follow the installation wizard.</li>
141
- <li>After installing the updated program, you can launch it from your desktop or start menu.</li>
142
- </ol>
143
- <h3>How to disable antivirus software while working with the program</h3>
144
- <p>Some antivirus software may detect Epson WF 7511 Adjustment Program as a malicious or suspicious program and block it from running or accessing your printer. This can cause errors or failures when using the program. To avoid this problem, you need to disable your antivirus software while working with the program or add the program to the exceptions list of your antivirus software.</p>
145
- <p>To disable your antivirus software, you need to follow these steps:</p>
146
- <ol>
147
- <li>Find your antivirus software icon on your taskbar or system tray and right-click on it.</li>
148
- <li>Select "Disable" or "Turn off" or similar option from the menu that appears.</li>
149
- <li>Select how long you want to disable your antivirus software for. You can choose from a few minutes to permanently.</li>
150
- <li>Click on "OK" or "Yes" or similar button to confirm your choice.</li>
151
- <li>Your antivirus software is now disabled and will not interfere with Epson WF 7511 Adjustment Program.</li>
152
- </ol>
153
- <p>To add Epson WF 7511 Adjustment Program to the exceptions list of your antivirus software, you need to follow these steps:</p>
154
- <ol>
155
- <li>Find your antivirus software icon on your taskbar or system tray and right-click on it.</li>
156
- <li>Select "Settings" or "Options" or similar option from the menu that appears.</li>
157
- <li>Select "Exceptions" or "Exclusions" or similar option from the settings menu.</li>
158
- <li>Select "Add" or "Browse" or similar button to add a new exception.</li>
159
- <li>Select the folder where you have installed Epson WF 7511 Adjustment Program and click on "OK" or "Open" or similar button.</li>
160
- <li>Your antivirus software will now allow Epson WF 7511 Adjustment Program to run and access your printer without any problems.</li>
161
- </ol>
162
- <h2>Conclusion</h2>
163
- <p>Epson WF 7511 Adjustment Program is a service adjustment program that can help you fix various problems with your Epson WF 7011 or WF 7511 printer, such as waste ink pad overflow, print head error, or printer initialization failure. It can also help you reset the waste ink pad counter, prescribe the print head ID, do printer initialization, and other functions for your printer. It is an original, full version, and updated program that has a simple user interface and easy-to-use features. It is compatible with Windows operating systems and works only with USB connection.</p>
164
- <p>If you are looking for a solution for your Epson printer problems, Epson WF 7511 Adjustment Program is a great choice for you. You can download and install it from <a href="https://orpys.com/en/epson/230-wf-7011-wf-7511-adjustment-program.html">this website</a>, which offers free updates and discounts for regular customers. You can also follow our guide on how to use it effectively and safely, and enjoy its features and benefits.</p>
165
- <p>Epson WF 7511 Adjustment Program can help you extend the lifespan of your printer and improve its performance and quality. It is a must-have tool for every Epson printer user. Don't hesitate and get it today!</p>
166
- <h3>Summary of the main points</h3>
167
- <ul><li>Epson WF 7511 Adjustment Program is a service adjustment program that can help you fix various problems with <li>It can help you reset the waste ink pad counter, prescribe the print head ID, do printer initialization, and other functions for your printer.</li>
168
- <li>It is an original, full version, and updated program that has a simple user interface and easy-to-use features.</li>
169
- <li>It is compatible with Windows operating systems and works only with USB connection.</li>
170
- </ul>
171
- <h3>Call to action</h3>
172
- <p>If you want to download and install Epson WF 7511 Adjustment Program, you can click on the button below and get it from <a href="https://orpys.com/en/epson/230-wf-7011-wf-7511-adjustment-program.html">this website</a>. You will also get free updates and discounts for regular customers. Don't miss this opportunity and get your Epson printer fixed today!</p>
173
- <p><a href="https://orpys.com/en/epson/230-wf-7011-wf-7511-adjustment-program.html"><button style="background-color: green; color: white; font-size: 20px; padding: 10px 20px; border-radius: 10px;">Download Epson WF 7511 Adjustment Program Now!</button></a></p>
174
- <h2>FAQs</h2>
175
- <p>Here are some frequently asked questions about Epson WF 7511 Adjustment Program:</p>
176
- <h4>Q: Is Epson WF 7511 Adjustment Program safe to use?</h4>
177
- <p>A: Yes, Epson WF 7511 Adjustment Program is safe to use. It is an original program that does not contain any viruses or malware. However, some antivirus software may detect it as a suspicious program and block it from running or accessing your printer. To avoid this problem, you need to disable your antivirus software while working with the program or add the program to the exceptions list of your antivirus software.</p>
178
- <h4>Q: Does Epson WF 7511 Adjustment Program work with other printer models?</h4>
179
- <p>A: No, Epson WF 7511 Adjustment Program works only with Epson WorkForce WF-7011 and WF-7511 printer models. It does not work with other printer models. If you have a different printer model, you need to find a different adjustment program that is compatible with your printer model.</p>
180
- <h4>Q: How often do I need to use Epson WF 7511 Adjustment Program?</h4>
181
- <p>A: You need to use Epson WF 7511 Adjustment Program whenever you encounter a problem with your printer that can be solved by using the program. For example, if your printer displays an error message about waste ink pad overflow, you need to use the program to reset the waste ink pad counter. If your printer does not recognize your print head, you need to use the program to prescribe the print head ID. If your printer settings are corrupted or incorrect, you need to use the program to do printer initialization.</p>
182
- <h4>Q: How long does it take to use Epson WF 7511 Adjustment Program?</h4>
183
- <p>A: It depends on the function you want to perform and the speed of your computer and printer. Generally, it takes a few minutes to use Epson WF 7511 Adjustment Program for each function. For example, it takes about 2 minutes to reset the waste ink pad counter, about 3 minutes to prescribe the print head ID, and about 5 minutes to do printer initialization.</p>
184
- <h4>Q: What are the advantages of using Epson WF 7511 Adjustment Program?</h4>
185
- <p>A: There are many advantages of using Epson WF 7511 Adjustment Program for your printer. Some of them are:</p>
186
- <ul>
187
- <li>You can fix various problems with your printer without having to take it to a service center or buy a new one.</li>
188
- <li>You can extend the lifespan of your printer and improve its performance and quality.</li>
189
- <li>You can save money and time by using the program yourself instead of paying for professional services or products.</li>
190
- <li>You can learn more about your printer and how it works by using the program.</li>
191
- </ul>
192
- </p> 0a6ba089eb<br />
193
- <br />
194
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1acneusushi/gradio-2dmoleculeeditor/data/Family Tree Maker For Mac 2 Torrent ((INSTALL)).md DELETED
@@ -1,111 +0,0 @@
1
- <br />
2
- <h1>Family Tree Maker For Mac 2 Torrent: How to Download and Use It</h1>
3
- <p>If you are interested in tracing your roots and creating a family tree, you might have heard of Family Tree Maker, one of the most popular genealogy software in the market. But what if you have a Mac computer and you don't want to pay for the software? Is there a way to get it for free? The answer is yes, if you use a torrent file. In this article, we will explain what Family Tree Maker is, what a torrent file is, why you might want to use Family Tree Maker For Mac 2 Torrent, and how to download and use it. Read on to find out more.</p>
4
- <h2>Introduction</h2>
5
- <h3>What is Family Tree Maker?</h3>
6
- <p>Family Tree Maker is a software that helps you create and share your family tree. It allows you to add information about your ancestors and relatives, such as names, dates, places, events, photos, documents, stories, and more. You can also import data from historical records and official archives, such as census records, birth certificates, marriage licenses, death certificates, military records, immigration records, etc. You can also collaborate with other family history enthusiasts online and compare notes and discover more together. Family Tree Maker also lets you share and print your family tree in various formats, such as charts, reports, books, slideshows, etc.</p>
7
- <h2>Family Tree Maker For Mac 2 Torrent</h2><br /><p><b><b>Download</b> <a href="https://byltly.com/2uKwHA">https://byltly.com/2uKwHA</a></b></p><br /><br />
8
- <h3>What is a torrent file?</h3>
9
- <p>A torrent file is a small file that contains information about a larger file or a group of files that you want to download from the internet. It does not contain the actual files themselves, but rather the metadata, such as the file names, sizes, locations, checksums, etc. A torrent file also contains information about the peers or sources that have the files or parts of the files that you want to download. To download a torrent file, you need a torrent client, which is a software that connects you to the peers and downloads the files for you.</p>
10
- <h3>Why use Family Tree Maker For Mac 2 Torrent?</h3>
11
- <p>There are several reasons why you might want to use Family Tree Maker For Mac 2 Torrent instead of buying the software from the official website. Here are some of them:</p>
12
- <ul>
13
- <li>You can save money. The official price of Family Tree Maker for Mac is $39.95, which might be too expensive for some people. By using a torrent file, you can get it for free.</li>
14
- <li>You can get an older version. The latest version of Family Tree Maker for Mac is version 24, which was released in 2020. However, some users might prefer an older version, such as version 2, which was released in 2011. By using a torrent file, you can choose which version you want to download.</li>
15
- <li>You can avoid compatibility issues. The latest version of Family Tree Maker for Mac requires macOS Catalina or later, which might not be compatible with some older Mac computers. By using an older version of Family Tree Maker for Mac via torrent file, you can avoid this problem.</li>
16
- </ul>
17
- <h2 <h2>How to download Family Tree Maker For Mac 2 Torrent</h2>
18
- <p>Now that you know what Family Tree Maker For Mac 2 Torrent is and why you might want to use it, let's see how you can download it. Here are the steps you need to follow:</p>
19
- <h3>Step 1: Find a reliable torrent site</h3>
20
- <p>The first thing you need to do is to find a torrent site that has the Family Tree Maker For Mac 2 Torrent file that you want. A torrent site is a website that hosts and indexes torrent files from various sources. There are many torrent sites on the internet, but not all of them are safe and trustworthy. Some of them might have malware, viruses, fake files, or illegal content. Therefore, you need to be careful and choose a reputable and reliable torrent site. Here are some of the factors you should consider when choosing a torrent site:</p>
21
- <ul>
22
- <li>The number and quality of torrents. A good torrent site should have a large and diverse collection of torrents, covering different categories, genres, languages, and formats. The torrents should also have high quality, meaning they should have good resolution, sound, subtitles, etc.</li>
23
- <li>The number and availability of peers. A good torrent site should have a high number of peers or sources for each torrent file, meaning there are many people who have the files or parts of the files that you want to download. The peers should also be available and online most of the time, meaning they are willing to share the files with you.</li>
24
- <li>The speed and security of downloads. A good torrent site should have a fast and stable download speed, meaning you can get the files you want quickly and without interruptions. The torrent site should also have a secure and encrypted connection, meaning your downloads are protected from hackers, trackers, or spies.</li>
25
- <li>The reputation and reviews of users. A good torrent site should have a positive reputation and feedback from other users, meaning they have used the site before and had a good experience with it. You can check the ratings, comments, reviews, or testimonials of other users on the torrent site itself or on other websites or forums.</li>
26
- </ul>
27
- <p>Some examples of reliable torrent sites that might have Family Tree Maker For Mac 2 Torrent are The Pirate Bay, RARBG, 1337x, etc. However, these sites might be blocked or banned in some countries or regions due to legal issues or censorship. Therefore, you might need to use a VPN (virtual private network) service to access them. A VPN service is a software that creates a secure and encrypted connection between your device and a server in another location, allowing you to bypass geo-restrictions and access any website you want.</p>
28
- <h3>Step 2: Search for Family Tree Maker For Mac 2 Torrent</h3>
29
- <p>Once you have found a reliable torrent site, the next thing you need to do is to search for Family Tree Maker For Mac 2 Torrent on it. You can use the search bar or the filters on the torrent site to find the torrent file that matches your criteria. You can type in keywords such as "Family Tree Maker", "Mac", "version 2", "torrent", etc. You can also filter by category, genre, language, format, size, date, etc.</p>
30
- <p>When you see the list of results, you should look at the details of each torrent file before downloading it. Here are some of the details you should pay attention to:</p>
31
- <p></p>
32
- <ul>
33
- <li>The name and description of the torrent file. The name and description should match what you are looking for and provide relevant information about the content and quality of the file.</li>
34
- <li>The size and type of the file. The size and type should indicate how much space the file will take on your device and what format it is in. For example, if you are looking for a software file, it should be in .exe or .dmg format.</li>
35
- <li>The number of seeders and leechers. The number of seeders and leechers should indicate how popular and available the file is. Seeders are people who have the complete file and are sharing it with others. Leechers are people who are downloading the file or parts of it from others. Ideally, you should choose a torrent file that has more seeders than leechers.</li>
36
- <li>The rating and comments of other users. The rating and comments should indicate how satisfied and trustworthy other users are with the file. Ideally, you should choose a torrent file that has a high rating and positive comments.</li>
37
- </ul>
38
- <p>Some examples of Family Tree Maker For Mac 2 Torrent files that you might find on a torrent site are:</p>
39
- | Name | Size | Type | Seeders | Leechers | Rating | Comments | | --- | --- | --- | --- | --- | --- | --- | Name | Size | Type | Seeders | Leechers | Rating | Comments | | --- | --- | --- | --- | --- | --- | --- | | Family Tree Maker for Mac 2 (2011) - Full Version [Mac OSX] | 1.2 GB | .dmg | 125 | 12 | 4.5/5 | "Works great, easy to install, no problems" | | Family Tree Maker for Mac 2 (2011) - Crack Only [Mac OSX] | 12 MB | .zip | 87 | 9 | 4/5 | "You need to disable your antivirus before running the crack, otherwise it won't work" | | Family Tree Maker for Mac 2 (2011) - Update Only [Mac OSX] | 150 MB | .dmg | 65 | 7 | 3.5/5 | "This update fixes some bugs and improves performance, but you need to have the full version installed first" | <p>Choose the torrent file that suits your needs and preferences, and click on the download button or link to get it.</p>
40
- <h3>Step 3: Download the torrent file</h3>
41
- <p>After you click on the download button or link, you will be prompted to save the torrent file on your device. Choose a location where you want to save it, such as your desktop or downloads folder. The torrent file should be very small and quick to download, usually less than a few megabytes.</p>
42
- <h3>Step 4: Open the torrent file with a torrent client</h3>
43
- <p>Once you have downloaded the torrent file, you need to open it with a torrent client. A torrent client is a software that connects you to the peers or sources that have the files or parts of the files that you want to download. It also manages the download process and ensures that you get the complete and correct files. There are many torrent clients available for Mac, such as uTorrent, BitTorrent, Transmission, qBittorrent, etc. You can choose one that suits your needs and preferences, and download and install it on your device.</p>
44
- <p>After you have installed a torrent client, you need to open the torrent file with it. You can do this by double-clicking on the torrent file, or by dragging and dropping it into the torrent client window, or by clicking on File > Open Torrent in the torrent client menu. The torrent client will then scan the torrent file and show you the details of the files that you are about to download, such as the name, size, type, progress, speed, etc. You can also choose which files you want to download or skip, and where you want to save them on your device.</p>
45
- <p>Click on the start or play button to begin the download. The torrent client will then connect you to the peers or sources that have the files or parts of the files that you want to download. It will also show you the status of the download, such as the number of seeders and leechers, the download and upload speed, the estimated time remaining, etc. You can pause or resume the download at any time, or cancel it if you change your mind.</p>
46
- <p>Wait until the download is complete. The time it takes to download depends on various factors, such as the size and quality of the files, the number and availability of peers or sources, the speed and stability of your internet connection, etc. It might take from a few minutes to a few hours or even days.</p>
47
- <h2>How to use Family Tree Maker For Mac 2 Torrent</h2>
48
- <p>Now that you have downloaded Family Tree Maker For Mac 2 Torrent, let's see how you can use it. Here are the steps you need to follow:</p>
49
- <h3>Step 1: Install Family Tree Maker on your Mac</h3>
50
- <p>The first thing you need to do is to install Family Tree Maker on your Mac. To do this, you need to locate the installation file that you downloaded via torrent. It should be in .dmg format, which is a disk image file that contains the software and its components. Double-click on the .dmg file to open it. You will see a window that shows the contents of the disk image file, such as an icon of Family Tree Maker and a shortcut to your Applications folder.</p>
51
- <p>Drag and drop the icon of Family Tree Maker into your Applications folder. This will copy the software into your Applications folder and create a shortcut for it. Alternatively, you can run the installer program that is included in the disk image file and follow the instructions on screen.</p>
52
- <p>If you downloaded a crack file or an update file via torrent, you might need to apply them before or after installing Family Tree Maker. A crack file is a file that modifies or bypasses the security features of a software, such as activation codes or serial numbers, allowing you to use the software for free or without limitations. An update file is a file that improves or fixes the software, such as adding new features or resolving bugs or errors. To apply a crack file or an update file, you need to locate them on your device and follow the instructions that are usually included in a text file or a readme file. You might need to copy and paste the crack file or the update file into the installation folder of Family Tree Maker, or run them as administrator, or restart your Mac, etc.</p>
53
- <h3>Step 2: Create or import your family tree</h3>
54
- <p>After you have installed Family Tree Maker on your Mac, you can launch it from your Applications folder or from your Dock. You will see a welcome screen that gives you two options: create a new family tree or import an existing family tree.</p>
55
- <p>If you want to create a new family tree, you can click on the New button and enter a name for your family tree. You can also choose a template for your family tree, such as standard, extended, fan, bow tie, etc. You can also customize the appearance of your family tree, such as the color, font, style, etc.</p>
56
- <p>If you want to import an existing family tree, you can click on the Import button and browse for the file that contains your family tree data. Family Tree Maker supports various file formats, such as .ftm, .ftmb, .ftw, .ged, etc. You can also import data from online sources, such as Ancestry.com, FamilySearch.org, etc. You will need to sign in with your account and grant permission to Family Tree Maker to access your data.</p>
57
- <h3>Step 3: Add and edit information about your ancestors and relatives</h3>
58
- <p>Once you have created or imported your family tree, you can start adding and editing information about your ancestors and relatives. You can do this by clicking on the People tab and selecting the person you want to work on. You will see a panel that shows the details of the person, such as name, birth date and place, death date and place, gender, occupation, etc. You can also see the relationships of the person with other people in your family tree, such as parents, spouse, children, siblings, etc.</p>
59
- <p>To add information about a person, you can click on the Add button and choose what kind of information you want to add. For example, you can add facts, events, notes, sources, media, etc. You can also add new people to your family tree by clicking on the Add button and choosing what kind of relationship you want to add. For example, you can add parents, spouse, children, siblings, etc.</p>
60
- <p>To edit information about a person, you can click on the Edit button and make changes to the existing information. For example, you can change the name, date, place, source, media, etc. of the person. You can also delete information or people from your family tree by clicking on the Delete button and confirming your action.</p>
61
- <h3>Step 4: Attach photos, documents, and stories to your family tree</h3>
62
- <p>One of the best features of Family Tree Maker is that it allows you to attach photos, documents, and stories to your family tree. This can help you enrich your family history and make it more personal and memorable. You can do this by clicking on the Media tab and selecting the person you want to work on. You will see a panel that shows the media items that are attached to the person, such as photos, documents, audio files, video files, etc.</p>
63
- <p>To attach a photo or a document to a person, you can click on the Add button and choose what kind of media item you want to add. For example, you can add a photo from your computer, from your camera, from a scanner, from a web address, etc. You can also add a document from your computer, from a scanner, from a web address, etc. You can also drag and drop media items from your computer or other sources into the panel.</p>
64
- <p>To attach a story to a person, you can click on the Add button and choose Story. You will see a window where you can write or paste your story. You can also format your story using various tools, such as font, size, color, alignment, bullet points, etc. You can also add photos or documents to your story by clicking on the Insert button and choosing what kind of media item you want to add.</p>
65
- <p>To edit or delete a media item or a story that is attached to a person, you can click on the Edit or Delete button and make changes or confirm your action.</p>
66
- <h3>Step 5: Share and print your family tree</h3>
67
- <p>After you have added and edited information and media items to your family tree, you might want to share and print it. Family Tree Maker offers various options for sharing and printing your family tree. You can do this by clicking on the Publish tab and selecting what kind of output you want to create. For example, you can create charts, reports, books, slideshows, etc.</p>
68
- <p>To create a chart of your family tree, you can click on the Chart button and choose what kind of chart you want to create. For example, you can create a pedigree chart, a descendant chart, a fan chart, a bow tie chart, etc. You can also customize the appearance of your chart, such as the size, shape, color, font, style, etc. You can also add or remove information and media items from your chart, such as names, dates, places, photos, etc.</p>
69
- <p>To create a report of your family tree, you can click on the Report button and choose what kind of report you want to create. For example, you can create a family group sheet, a kinship report, a timeline report, a source report, etc. You can also customize the content and format of your report, such as the fields, filters, sorting, layout, etc. You can also add or remove information and media items from your report, such as names, dates, places, photos, etc.</p>
70
- <p>To create a book of your family tree, you can click on the Book button and choose what kind of book you want to create. For example, you can create a narrative book, a scrapbook, a photo book, etc. You can also customize the design and layout of your book, such as the cover, title page, table of contents, chapters, sections, pages, etc. You can also add or remove information and media items from your book, such as names, dates, places, photos, stories, etc.</p>
71
- <p>To create a slideshow of your family tree, you can click on the Slideshow button and choose what kind of slideshow you want to create. For example, you can create a standard slideshow, a photo slideshow, a video slideshow, etc. You can also customize the settings and effects of your slideshow, such as the duration, transition, music, narration, etc. You can also add or remove information and media items from your slideshow, such as names, dates, places, photos, stories, etc.</p>
72
- <p>After you have created your output, you can preview it on your screen and make any adjustments if needed. You can also share it online or print it on paper or other materials. To share your output online, you can click on the Share button and choose what kind of platform you want to use. For example, you can share your output on Ancestry.com, FamilySearch.org, Facebook, Twitter, email, etc. You will need to sign in with your account and grant permission to Family Tree Maker to access your data. To print your output on paper or other materials, you can click on the Print button and choose what kind of printer and settings you want to use. For example, you can print your output on letter size paper, legal size paper, poster size paper, canvas, t-shirt, mug, etc.</p>
73
- <h2>Conclusion</h2>
74
- <p>In conclusion, Family Tree Maker For Mac 2 Torrent is a great way to create and share your family tree without paying for the software or worrying about compatibility issues. You can download and use it by following these steps:</p>
75
- <ol>
76
- <li>Find a reliable torrent site that has the Family Tree Maker For Mac 2 Torrent file that you want.</li>
77
- <li>Search for Family Tree Maker For Mac 2 Torrent on the torrent site and download the torrent file.</li>
78
- <li>Open the torrent file with a torrent client and download the files that you want.</li>
79
- <li>Install Family Tree Maker on your Mac and apply any crack or update files if needed.</li>
80
- <li>Create or import your family tree and add and edit information and media items about your ancestors and relatives.</li>
81
- <li>Share and print your family tree in various formats, such as charts, reports, books, slideshows, etc.</li>
82
- </ol>
83
- <p>We hope this article has helped you understand how to download and use Family Tree Maker For Mac 2 Torrent. If you have any questions or comments, please feel free to leave them below. Happy genealogy!</p>
84
- <h3>FAQs</h3>
85
- <p>Here are some of the frequently asked questions about Family Tree Maker For Mac 2 Torrent:</p>
86
- <h4>Is Family Tree Maker For Mac 2 Torrent legal?</h4>
87
- <p>Family Tree Maker For Mac 2 Torrent is not legal in most countries or regions. It is considered a form of piracy or intellectual property theft, as it violates the rights of the software developers and distributors. Downloading and using Family Tree Maker For Mac 2 Torrent might expose you to legal risks or penalties, such as fines, lawsuits, or even jail time. Therefore, we do not recommend or endorse using Family Tree Maker For Mac 2 Torrent, and we advise you to use it at your own risk and discretion.</p>
88
- <h4>Is Family Tree Maker For Mac 2 Torrent safe?</h4>
89
- <p>Family Tree Maker For Mac 2 Torrent is not safe in most cases. It might contain malware, viruses, spyware, adware, or other harmful programs that can damage your device or compromise your privacy and security. Downloading and using Family Tree Maker For Mac 2 Torrent might expose you to cyber risks or threats, such as hacking, phishing, identity theft, data loss, etc. Therefore, we do not recommend or endorse using Family Tree Maker For Mac 2 Torrent, and we advise you to use it at your own risk and discretion.</p>
90
- <h4>How to update Family Tree Maker For Mac 2 Torrent?</h4>
91
- <p>Family Tree Maker For Mac 2 Torrent is an outdated version of the software that was released in 2011. It might not have the latest features, functions, or improvements that the current version of Family Tree Maker has. It might also have some bugs, errors, or compatibility issues that affect its performance or usability. To update Family Tree Maker For Mac 2 Torrent, you might need to download and apply an update file via torrent. However, this might not be easy or possible, as the update file might not be available or reliable on torrent sites. Therefore, we do not recommend or endorse using Family Tree Maker For Mac 2 Torrent, and we advise you to use the latest version of Family Tree Maker instead.</p>
92
- <h4>How to uninstall Family Tree Maker For Mac 2 Torrent?</h4>
93
- <p>If you want to uninstall Family Tree Maker For Mac 2 Torrent from your Mac, you can follow these steps:</p>
94
- <ol>
95
- <li>Open your Applications folder and find the icon of Family Tree Maker.</li>
96
- <li>Drag and drop the icon of Family Tree Maker into the Trash bin.</li>
97
- <li>Empty the Trash bin to delete the software and its components.</li>
98
- <li>Open your Finder and go to the Library folder.</li>
99
- <li>Search for any files or folders that are related to Family Tree Maker and delete them.</li>
100
- </ol>
101
- <p>This should remove Family Tree Maker For Mac 2 Torrent from your Mac. However, this might not remove all the traces or remnants of the software from your device. To completely uninstall Family Tree Maker For Mac 2 Torrent from your Mac, you might need to use a third-party uninstaller program that can scan and delete any leftover files or registry entries of the software.</p>
102
- <h4>What are some alternatives to Family Tree Maker For Mac 2 Torrent?</h4>
103
- <p>If you are looking for some alternatives to Family Tree Maker For Mac 2 Torrent, here are some of them:</p>
104
- <ul>
105
- <li>Family Tree Builder: This is a free genealogy software that helps you create and share your family tree. It has similar features and functions as Family Tree Maker, such as adding information and media items about your ancestors and relatives, importing data from online sources, sharing and printing your family tree in various formats, etc. You can download it from <a href="">https://www.myheritage.com/family-tree-builder</a>.</li>
106
- <li>Gramps: This is a free and open-source genealogy software that helps you create and share your family tree. It has similar features and functions as Family Tree Maker, such as adding information and media items about your ancestors and relatives, importing data from online sources, sharing and printing your family tree in various formats, etc. You can download it from <a href="">https://gramps-project.org/</a>.</li>
107
- <li>MacFamilyTree: This is a paid genealogy software that helps you create and share your family tree. It has similar features and functions as Family Tree Maker, such as adding information and media items about your ancestors and relatives, importing data from online sources, sharing and printing your family tree in various formats, etc. It also has some unique features, such as creating interactive family maps, timelines, statistics, charts, etc. You can buy it from <a href="">https://www.syniumsoftware.com/macfamilytree</a>.</li>
108
- </ul>
109
- <p>These are some of the alternatives to Family Tree Maker For Mac 2 Torrent that you can try. However, none of them can replace the original and official version of Family Tree Maker, which has the best quality, support, and updates. Therefore, we recommend that you buy Family Tree Maker from the official website if you can afford it and enjoy its full benefits.</p> b2dd77e56b<br />
110
- <br />
111
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1gistliPinn/ChatGPT4/Examples/Deluxe Ski Jump 3 V1.7.1 Keygen !!EXCLUSIVE!!.md DELETED
@@ -1,7 +0,0 @@
1
- <br />
2
- <p> <p> <p> <p> deluxe ski jump 3 v1.7.1 keygen <p> <strong> Other reviews: <br> The Legend of Zelda: Breath of the Wild lets you go anywhere and do anything. Throw a rock, find a new path, explore. The freedom the game offers is exhausting, and I don't know how many times I had to pause to catch my breath. Sure, collecting the Master Sword and fighting Ganon wasn't challenging, but a rich world full of secrets, opportunities, and hidden treasures is a lot more rewarding.</strong></p>
3
- <p> <p> <p> deluxe ski jump 3 v1.7.1 keygen <p> <strong> This version comes with a brand new story and nine brand new modes to play. For an action game, it's not bad at all. None of the modes are replayable, so they're only there to give you something to do. As a matter of fact, I couldn't even finish the story because I needed to stop to check out the different modes and achievements. Unfortunately, the time I spent playing these modes couldn't be easily returned. </strong></p>
4
- <h2>deluxe ski jump 3 v1.7.1 keygen</h2><br /><p><b><b>DOWNLOAD</b> &#9745; <a href="https://imgfil.com/2uy0py">https://imgfil.com/2uy0py</a></b></p><br /><br />
5
- <p> <p> <p> deluxe ski jump 3 v1.7.1 keygen <p> <strong> My only complaint is that the game seems to repeat sections that got me far enough into the story. It's a minor issue, but I had to beat a bunch of story cutscenes twice because I couldn't make it through them the first time. Also, it seems that the game is never really "over" until I start a new game and try again, and that's a bit of a turn-off. All of that said, this game is a great game. The story, music, and visuals are top-notch, and the hack and slash action is even better than in the previous games.</strong></p> 899543212b<br />
6
- <br />
7
- <br />
 
 
 
 
 
 
 
 
spaces/1gistliPinn/ChatGPT4/Examples/Free Acme Id Card Maker 5.0 Serial Keygen !!EXCLUSIVE!!.md DELETED
@@ -1,6 +0,0 @@
1
- <h2>free acme id card maker 5.0 serial keygen</h2><br /><p><b><b>Download</b> &#9658;&#9658;&#9658; <a href="https://imgfil.com/2uy1EY">https://imgfil.com/2uy1EY</a></b></p><br /><br />
2
- <br />
3
- Free Photo Card Workshop Download, Photo Card Workshop 1.5 ... Please be aware that Brothersoft do not supply any crack, patches, serial numbers or keygen for Photo Card ... Acme Id Card Maker V5.0 Crack ->Shutdown. 1fdad05405<br />
4
- <br />
5
- <br />
6
- <p></p>
 
 
 
 
 
 
 
spaces/1line/AutoGPT/autogpt/commands/file_operations.py DELETED
@@ -1,267 +0,0 @@
1
- """File operations for AutoGPT"""
2
- from __future__ import annotations
3
-
4
- import os
5
- import os.path
6
- from typing import Generator
7
-
8
- import requests
9
- from colorama import Back, Fore
10
- from requests.adapters import HTTPAdapter, Retry
11
-
12
- from autogpt.spinner import Spinner
13
- from autogpt.utils import readable_file_size
14
- from autogpt.workspace import WORKSPACE_PATH, path_in_workspace
15
-
16
- LOG_FILE = "file_logger.txt"
17
- LOG_FILE_PATH = WORKSPACE_PATH / LOG_FILE
18
-
19
-
20
- def check_duplicate_operation(operation: str, filename: str) -> bool:
21
- """Check if the operation has already been performed on the given file
22
-
23
- Args:
24
- operation (str): The operation to check for
25
- filename (str): The name of the file to check for
26
-
27
- Returns:
28
- bool: True if the operation has already been performed on the file
29
- """
30
- log_content = read_file(LOG_FILE)
31
- log_entry = f"{operation}: {filename}\n"
32
- return log_entry in log_content
33
-
34
-
35
- def log_operation(operation: str, filename: str) -> None:
36
- """Log the file operation to the file_logger.txt
37
-
38
- Args:
39
- operation (str): The operation to log
40
- filename (str): The name of the file the operation was performed on
41
- """
42
- log_entry = f"{operation}: {filename}\n"
43
-
44
- # Create the log file if it doesn't exist
45
- if not os.path.exists(LOG_FILE_PATH):
46
- with open(LOG_FILE_PATH, "w", encoding="utf-8") as f:
47
- f.write("File Operation Logger ")
48
-
49
- append_to_file(LOG_FILE, log_entry, shouldLog=False)
50
-
51
-
52
- def split_file(
53
- content: str, max_length: int = 4000, overlap: int = 0
54
- ) -> Generator[str, None, None]:
55
- """
56
- Split text into chunks of a specified maximum length with a specified overlap
57
- between chunks.
58
-
59
- :param content: The input text to be split into chunks
60
- :param max_length: The maximum length of each chunk,
61
- default is 4000 (about 1k token)
62
- :param overlap: The number of overlapping characters between chunks,
63
- default is no overlap
64
- :return: A generator yielding chunks of text
65
- """
66
- start = 0
67
- content_length = len(content)
68
-
69
- while start < content_length:
70
- end = start + max_length
71
- if end + overlap < content_length:
72
- chunk = content[start : end + overlap - 1]
73
- else:
74
- chunk = content[start:content_length]
75
-
76
- # Account for the case where the last chunk is shorter than the overlap, so it has already been consumed
77
- if len(chunk) <= overlap:
78
- break
79
-
80
- yield chunk
81
- start += max_length - overlap
82
-
83
-
84
- def read_file(filename: str) -> str:
85
- """Read a file and return the contents
86
-
87
- Args:
88
- filename (str): The name of the file to read
89
-
90
- Returns:
91
- str: The contents of the file
92
- """
93
- try:
94
- filepath = path_in_workspace(filename)
95
- with open(filepath, "r", encoding="utf-8") as f:
96
- content = f.read()
97
- return content
98
- except Exception as e:
99
- return f"Error: {str(e)}"
100
-
101
-
102
- def ingest_file(
103
- filename: str, memory, max_length: int = 4000, overlap: int = 200
104
- ) -> None:
105
- """
106
- Ingest a file by reading its content, splitting it into chunks with a specified
107
- maximum length and overlap, and adding the chunks to the memory storage.
108
-
109
- :param filename: The name of the file to ingest
110
- :param memory: An object with an add() method to store the chunks in memory
111
- :param max_length: The maximum length of each chunk, default is 4000
112
- :param overlap: The number of overlapping characters between chunks, default is 200
113
- """
114
- try:
115
- print(f"Working with file {filename}")
116
- content = read_file(filename)
117
- content_length = len(content)
118
- print(f"File length: {content_length} characters")
119
-
120
- chunks = list(split_file(content, max_length=max_length, overlap=overlap))
121
-
122
- num_chunks = len(chunks)
123
- for i, chunk in enumerate(chunks):
124
- print(f"Ingesting chunk {i + 1} / {num_chunks} into memory")
125
- memory_to_add = (
126
- f"Filename: {filename}\n" f"Content part#{i + 1}/{num_chunks}: {chunk}"
127
- )
128
-
129
- memory.add(memory_to_add)
130
-
131
- print(f"Done ingesting {num_chunks} chunks from {filename}.")
132
- except Exception as e:
133
- print(f"Error while ingesting file '{filename}': {str(e)}")
134
-
135
-
136
- def write_to_file(filename: str, text: str) -> str:
137
- """Write text to a file
138
-
139
- Args:
140
- filename (str): The name of the file to write to
141
- text (str): The text to write to the file
142
-
143
- Returns:
144
- str: A message indicating success or failure
145
- """
146
- if check_duplicate_operation("write", filename):
147
- return "Error: File has already been updated."
148
- try:
149
- filepath = path_in_workspace(filename)
150
- directory = os.path.dirname(filepath)
151
- if not os.path.exists(directory):
152
- os.makedirs(directory)
153
- with open(filepath, "w", encoding="utf-8") as f:
154
- f.write(text)
155
- log_operation("write", filename)
156
- return "File written to successfully."
157
- except Exception as e:
158
- return f"Error: {str(e)}"
159
-
160
-
161
- def append_to_file(filename: str, text: str, shouldLog: bool = True) -> str:
162
- """Append text to a file
163
-
164
- Args:
165
- filename (str): The name of the file to append to
166
- text (str): The text to append to the file
167
-
168
- Returns:
169
- str: A message indicating success or failure
170
- """
171
- try:
172
- filepath = path_in_workspace(filename)
173
- with open(filepath, "a") as f:
174
- f.write(text)
175
-
176
- if shouldLog:
177
- log_operation("append", filename)
178
-
179
- return "Text appended successfully."
180
- except Exception as e:
181
- return f"Error: {str(e)}"
182
-
183
-
184
- def delete_file(filename: str) -> str:
185
- """Delete a file
186
-
187
- Args:
188
- filename (str): The name of the file to delete
189
-
190
- Returns:
191
- str: A message indicating success or failure
192
- """
193
- if check_duplicate_operation("delete", filename):
194
- return "Error: File has already been deleted."
195
- try:
196
- filepath = path_in_workspace(filename)
197
- os.remove(filepath)
198
- log_operation("delete", filename)
199
- return "File deleted successfully."
200
- except Exception as e:
201
- return f"Error: {str(e)}"
202
-
203
-
204
- def search_files(directory: str) -> list[str]:
205
- """Search for files in a directory
206
-
207
- Args:
208
- directory (str): The directory to search in
209
-
210
- Returns:
211
- list[str]: A list of files found in the directory
212
- """
213
- found_files = []
214
-
215
- if directory in {"", "/"}:
216
- search_directory = WORKSPACE_PATH
217
- else:
218
- search_directory = path_in_workspace(directory)
219
-
220
- for root, _, files in os.walk(search_directory):
221
- for file in files:
222
- if file.startswith("."):
223
- continue
224
- relative_path = os.path.relpath(os.path.join(root, file), WORKSPACE_PATH)
225
- found_files.append(relative_path)
226
-
227
- return found_files
228
-
229
-
230
- def download_file(url, filename):
231
- """Downloads a file
232
- Args:
233
- url (str): URL of the file to download
234
- filename (str): Filename to save the file as
235
- """
236
- safe_filename = path_in_workspace(filename)
237
- try:
238
- message = f"{Fore.YELLOW}Downloading file from {Back.LIGHTBLUE_EX}{url}{Back.RESET}{Fore.RESET}"
239
- with Spinner(message) as spinner:
240
- session = requests.Session()
241
- retry = Retry(total=3, backoff_factor=1, status_forcelist=[502, 503, 504])
242
- adapter = HTTPAdapter(max_retries=retry)
243
- session.mount("http://", adapter)
244
- session.mount("https://", adapter)
245
-
246
- total_size = 0
247
- downloaded_size = 0
248
-
249
- with session.get(url, allow_redirects=True, stream=True) as r:
250
- r.raise_for_status()
251
- total_size = int(r.headers.get("Content-Length", 0))
252
- downloaded_size = 0
253
-
254
- with open(safe_filename, "wb") as f:
255
- for chunk in r.iter_content(chunk_size=8192):
256
- f.write(chunk)
257
- downloaded_size += len(chunk)
258
-
259
- # Update the progress message
260
- progress = f"{readable_file_size(downloaded_size)} / {readable_file_size(total_size)}"
261
- spinner.update_message(f"{message} {progress}")
262
-
263
- return f'Successfully downloaded and locally stored file: "{filename}"! (Size: {readable_file_size(total_size)})'
264
- except requests.HTTPError as e:
265
- return f"Got an HTTP Error whilst trying to download file: {e}"
266
- except Exception as e:
267
- return "Error: " + str(e)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/All-in-One Solitaire APK - The Ultimate Solitaire Collection for Android.md DELETED
@@ -1,93 +0,0 @@
1
-
2
- <h1>All-in-One Solitaire APK Download: Play Solitaire Games on Your Android Device</h1>
3
- <p>If you love playing solitaire games, you will love All-in-One Solitaire APK. This is an amazing app that lets you enjoy over 50 different solitaire games on your Android device. Whether you prefer classic solitaire games like Klondike, Spider, or FreeCell, or you want to try something new like Pyramid, Tri-Peaks, or Wasp, you will find them all in this app. You can also customize your cards and backgrounds, use unlimited undos and hints, and play offline or online. In this article, we will tell you more about All-in-One Solitaire APK, how to download and install it, how to play it, and why you should play it.</p>
4
- <h2>all in one solitaire apk download</h2><br /><p><b><b>Download File</b> &rArr;&rArr;&rArr; <a href="https://urlin.us/2uSUgc">https://urlin.us/2uSUgc</a></b></p><br /><br />
5
- <h2>What is All-in-One Solitaire APK?</h2>
6
- <p>All-in-One Solitaire APK is an Android game app that offers you a collection of over 50 solitaire games in one place. It is developed by Pozirk Games Inc., a company that specializes in creating casual games for mobile devices. The app has been downloaded over 1 million times on Google Play Store and has received positive reviews from users. The app is compatible with Android 5.0 and up and requires 20 MB of storage space.</p>
7
- <h3>Features of All-in-One Solitaire APK</h3>
8
- <h4>Over 50 solitaire games in one app</h4>
9
- <p>One of the best features of All-in-One Solitaire APK is that it gives you access to over 50 solitaire games in one app. You can choose from popular solitaire games like Klondike, Spider, FreeCell, Pyramid, Tri-Peaks, Crescent, Scorpion, Gaps, and more. You can also discover new solitaire games like Algerian, Calculation, Canfield, Flower Garden, Golf, Penguin, Terrace, Wasp, and more. Each game has its own rules and instructions that you can read before playing.</p>
10
- <h4>Unlimited undos and hints</h4>
11
- <p>Another great feature of All-in-One Solitaire APK is that it allows you to use unlimited undos and hints. If you make a mistake or get stuck, you can use the undo button to go back to your previous move. If you need some help or guidance, you can use the hint button to get a suggestion for your next move. These features make the game more enjoyable and less frustrating.</p>
12
- <h4>High quality cards and backgrounds</h4>
13
- <p>All-in-One Solitaire APK also offers you high quality cards and backgrounds that make the game more attractive and appealing. You can customize your cards by choosing from different designs, colors, sizes, and fonts. You can also change your backgrounds by selecting from various themes, patterns, and images. You can even use your own photos as backgrounds if you want.</p>
14
- <h4>Easy card movement with one tap</h4 <p>All-in-One Solitaire APK also makes the card movement easy and smooth with one tap. You don't have to drag and drop cards to move them, you can just tap on them and they will automatically move to the best possible place. This feature saves you time and effort and makes the game more convenient and user-friendly.</p>
15
- <p>All-in-One Solitaire Android Game Free Download<br />
16
- Download All in One Solitaire APK for Android Aptoide<br />
17
- All-in-One Solitaire 1.14.2 APK by Pozirk Games Inc.<br />
18
- Solitaire All-in-One Card Games APK Download<br />
19
- All in One Solitaire Free APK for Android Devices<br />
20
- All-in-One Solitaire APKCombo Games Card<br />
21
- All-in-One Solitaire Latest Version APK Update<br />
22
- Download All-in-One Solitaire 1.3.3 APK Aptoide<br />
23
- All-in-One Solitaire Game Features and Description<br />
24
- How to Install All-in-One Solitaire APK on Android<br />
25
- All-in-One Solitaire User Ratings and Reviews<br />
26
- All-in-One Solitaire Available Games and Modes<br />
27
- All-in-One Solitaire Unlimited Undos and Hints<br />
28
- All-in-One Solitaire Background Music and Sound Effects<br />
29
- All-in-One Solitaire Bigger and Better Cards<br />
30
- All-in-One Solitaire Easy Cards Movement with One Tap<br />
31
- All-in-One Solitaire Old Versions and History<br />
32
- All-in-One Solitaire Category and Google Play ID<br />
33
- All-in-One Solitaire Installs and Downloads Statistics<br />
34
- All-in-One Solitaire App APKs and Languages<br />
35
- All-in-One Solitaire Crescent Solitaire Game Mode<br />
36
- All-in-One Solitaire Cruel Solitaire Game Mode<br />
37
- All-in-One Solitaire Tri-Peaks Solitaire Game Mode<br />
38
- All-in-One Solitaire Pyramid Solitaire Game Mode<br />
39
- All-in-One Solitaire Klondike Solitaire Game Mode<br />
40
- All-in-One Solitaire Gaps Solitaire Game Mode<br />
41
- All-in-One Solitaire Spider Solitaire Game Mode<br />
42
- All-in-One Solitaire FreeCell Solitaire Game Mode<br />
43
- All-in-One Solitaire Fortune Solitaire Game Mode<br />
44
- All-in-One Solitaire Scorpion Solitaire Game Mode<br />
45
- All-in-One Solitaire Accordion Solitaire Game Mode<br />
46
- All-in-One Solitaire Penguin Solitaire Game Mode<br />
47
- All-in-One Solitaire 60/90 Seconds Solitaire Game Mode<br />
48
- All-in-One Solitaire Aces Up Solitaire Game Mode<br />
49
- All-in-One Solitaire Beehive Solitaire Game Mode<br />
50
- All-in-One Solitaire 40 Thieves Solitaire Game Mode<br />
51
- All-in-One Solitaire 52 Pickup Solitaire Game Mode<br />
52
- All-in-One Solitaire Algerian Solitaire Game Mode<br />
53
- All-in-One Solitaire Thieves Of Egypt Solitaire Game Mode<br />
54
- All-in-One Solitaire Wasp Solitaire Game Mode<br />
55
- All-in-One Solitaire Calculation Solitaire Game Mode<br />
56
- All-in-One Solitaire Canfield Solitaire Game Mode<br />
57
- All-in-One Solitaire Alternations Solitaire Game Mode<br />
58
- All-in-One Solitaire Yukon/Alaska/SolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameMode</p>
59
- <h3>How to download and install All-in-One Solitaire APK?</h3>
60
- <p>If you want to download and install All-in-One Solitaire APK on your Android device, you can follow these simple steps:</p>
61
- <h4>Step 1: Go to the official website of All-in-One Solitaire APK</h4>
62
- <p>The first step is to go to the official website of All-in-One Solitaire APK, where you can find the latest version of the app and more information about it. You can use this link to access the website.</p>
63
- <h4>Step 2: Click on the download button and choose the version you want</h4>
64
- <p>The next step is to click on the download button on the website and choose the version of the app that you want. There are two versions available: one for Android 5.0 and up, and one for Android 4.0.3 and up. You can also see the size of the app and the number of downloads before downloading it.</p>
65
- <h4>Step 3: Allow unknown sources on your device settings</h4>
66
- <p>The third step is to allow unknown sources on your device settings, so that you can install apps from sources other than Google Play Store. To do this, go to your device settings, then security, then enable unknown sources. This will allow you to install All-in-One Solitaire APK without any problems.</p>
67
- <h4>Step 4: Open the downloaded file and install the app</h4>
68
- <p>The final step is to open the downloaded file and install the app on your device. You can find the file in your downloads folder or in your notifications bar. Once you open it, you will see a screen that asks you to confirm the installation. Click on install and wait for a few seconds until the app is installed. Then, you can open it and start playing solitaire games.</p>
69
- <h3>How to play All-in-One Solitaire APK?</h3>
70
- <p>Playing All-in-One Solitaire APK is easy and fun. Here are some tips on how to play it:</p>
71
- <h4>Choose a solitaire game from the menu</h4>
72
- <p>The first thing you need to do is to choose a solitaire game from the menu. You can scroll through the list of over 50 solitaire games and select the one that you like. You can also see a preview of each game and its difficulty level before choosing it.</p>
73
- <h4>Follow the rules and instructions of the game</h4>
74
- <p>The next thing you need to do is to follow the rules and instructions of the game that you chose. You can read them by clicking on the question mark icon on the top right corner of the screen. You can also pause or restart the game by clicking on the menu icon on the top left corner of the screen.</p>
75
- <h4>Drag and drop cards to move them or tap to select them</h4 <p>The main thing you need to do is to drag and drop cards to move them or tap to select them. You can move cards from one pile to another according to the rules of each game. You can also double tap on a card to move it automatically if possible. You can also use gestures like swipe or pinch to zoom in or out of the cards.</p>
76
- <h4>Use the undo and hint buttons if you get stuck</h4 <p>The last thing you need to do is to use the undo and hint buttons if you get stuck. You can use the undo button to go back to your previous move if you make a mistake or change your mind. You can use the hint button to get a suggestion for your next move if you don't know what to do. These buttons are located at the bottom of the screen.</p>
77
- <h3>Why should you play All-in-One Solitaire APK?</h3>
78
- <p>There are many reasons why you should play All-in-One Solitaire APK. Here are some of them:</p>
79
- <h4>It is fun and relaxing</h4 <p>All-in-One Solitaire APK is a fun and relaxing game that you can play anytime and anywhere. You can enjoy playing solitaire games without any stress or pressure. You can also listen to soothing music and sound effects while playing.</p>
80
- <h4>It improves your brain skills and memory</h4 <p>All-in-One Solitaire APK also improves your brain skills and memory by challenging your logic, strategy, concentration, and patience. You can exercise your mind by solving different puzzles and problems in each game. You can also improve your memory by remembering the cards and their positions in each game.</p>
81
- <h4>It offers a variety of challenges and difficulties</h4 <p>All-in-One Solitaire APK also offers a variety of challenges and difficulties that suit your preferences and skills. You can choose from easy, medium, hard, or expert modes in each game. You can also compete with other players online and see your rank and score on the leaderboard.</p>
82
- <h4>It works offline and online</h4 <p>All-in-One Solitaire APK also works offline and online, so you can play it without any internet connection or with a stable connection. You can play it offline if you want to save your data or battery, or if you don't have access to the internet. You can play it online if you want to sync your progress across devices, or if you want to play with other players.</p>
83
- <h2>Conclusion</h2>
84
- <p>All-in-One Solitaire APK is a wonderful app that lets you play over 50 solitaire games on your Android device. You can download and install it easily from the official website, and enjoy its features like unlimited undos and hints, high quality cards and backgrounds, easy card movement with one tap, and more. You can also improve your brain skills and memory, have fun and relax, and choose from different challenges and difficulties. You can also play it offline or online, depending on your preference. If you love solitaire games, you should definitely try All-in-One Solitaire APK.</p>
85
- <h3>FAQs</h3>
86
- <p>Here are some frequently asked questions about All-in-One Solitaire APK:</p>
87
- <h4>Is All-in-One Solitaire APK free?</h4 <p>Yes, All-in-One Solitaire APK is free to download and play. However, it contains ads that you can remove by purchasing the premium version of the app for $2.99.</p>
88
- <h4>Is All-in-One Solitaire APK safe?</h4 <p>Yes, All-in-One Solitaire APK is safe to download and install. It does not contain any viruses or malware that can harm your device or data. However, you should always download it from the official website or a trusted source to avoid any risks.</p>
89
- <h4>What are the requirements for All-in-One Solitaire APK?</h4 <p>The requirements for All-in-One Solitaire APK are Android 5.0 and up for the latest version of the app, and Android 4.0.3 and up for the older version of the app. You also need 20 MB of storage space on your device to install the app.</p>
90
- <h4>How can I contact the developer of All-in-One Solitaire APK?</h4 <p>You can contact the developer of All-in-One Solitaire APK by sending an email to [email protected] or by visiting their website at https://pozirk.com/.</p>
91
- <h4>Can I play All-in-One Solitaire APK on my PC?</h4 <p>No, All-in-One Solitaire APK is only available for Android devices. However, you can use an Android emulator like Bluestacks or Nox Player to run the app on your PC.</p> 197e85843d<br />
92
- <br />
93
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Black Clover Wallpapers Discover the Best HD and 4K Backgrounds for Anime Lovers.md DELETED
@@ -1,98 +0,0 @@
1
- <br />
2
- <h1>Black Clover Wallpaper: How to Decorate Your Device with Magic and Adventure</h1>
3
- <p>If you are a fan of fantasy, action, and comedy, you might have heard of <strong>Black Clover</strong>, a popular manga and anime series that follows the adventures of Asta, a boy who wants to become the Wizard King in a world where everyone has magic. Whether you are new to the series or a long-time follower, you might want to spice up your device with some <strong>Black Clover wallpaper</strong> that showcases your favorite characters, scenes, and themes from the story. In this article, we will tell you everything you need to know about Black Clover wallpaper, including what it is, why you should choose it, and how to find and download it.</p>
4
- <h2>What is Black Clover?</h2>
5
- <p>Before we dive into the details of Black Clover wallpaper, let us first give you a brief introduction to the manga and anime series that inspired it.</p>
6
- <h2>black clover wallpaper</h2><br /><p><b><b>Download</b> - <a href="https://urlin.us/2uSZbG">https://urlin.us/2uSZbG</a></b></p><br /><br />
7
- <h3>A brief introduction to the manga and anime series</h3>
8
- <p>Black Clover is a Japanese manga series written and illustrated by Yūki Tabata. It has been serialized in Shueisha's shōnen manga magazine Weekly Shōnen Jump since February 2015, with its chapters collected in 35 tankōbon volumes as of June 2023 . The manga has been adapted into an anime television series by Studio Pierrot, which aired from October 2017 to March 2021, with a total of 170 episodes . The anime is also available for streaming on platforms like Crunchyroll and Funimation.</p>
9
- <p>The story of Black Clover is set in a world where magic is everything. People are born with magical abilities that vary in power and type. They use grimoires, books that amplify their magic and allow them to cast spells. The most coveted grimoire is the four-leaf clover, which grants its wielder exceptional magic and luck. However, there is also a rare and mysterious five-leaf clover grimoire, which contains a devil that can grant anti-magic powers.</p>
10
- <p>black clover wallpaper asta<br />
11
- black clover wallpaper yuno<br />
12
- black clover wallpaper noelle<br />
13
- black clover wallpaper yami<br />
14
- black clover wallpaper secre<br />
15
- black clover wallpaper zenon<br />
16
- black clover wallpaper nero<br />
17
- black clover wallpaper 4k<br />
18
- black clover wallpaper hd<br />
19
- black clover wallpaper desktop<br />
20
- black clover wallpaper phone<br />
21
- black clover wallpaper iphone<br />
22
- black clover wallpaper android<br />
23
- black clover wallpaper laptop<br />
24
- black clover wallpaper pc<br />
25
- black clover wallpaper 1920x1080<br />
26
- black clover wallpaper 3840x2160<br />
27
- black clover wallpaper 4096x2703<br />
28
- black clover wallpaper asta and yuno<br />
29
- black clover wallpaper asta and yami<br />
30
- black clover wallpaper asta and liebe<br />
31
- black clover wallpaper asta devil form<br />
32
- black clover wallpaper asta demon union<br />
33
- black clover wallpaper yuno spirit dive<br />
34
- black clover wallpaper yuno vs zenon<br />
35
- black clover wallpaper noelle valkyrie dress<br />
36
- black clover wallpaper noelle and asta<br />
37
- black clover wallpaper noelle and mimosa<br />
38
- black clover wallpaper yami and charlotte<br />
39
- black clover wallpaper yami katana<br />
40
- black clover wallpaper secre swallowtail<br />
41
- black clover wallpaper secre and nero<br />
42
- black clover wallpaper zenon zogratis<br />
43
- black clover wallpaper zenon vs yuno<br />
44
- black clover wallpaper nero bird form<br />
45
- black clover wallpaper nero seal magic<br />
46
- black clover wallpaper anime characters<br />
47
- black clover wallpaper anime scenes<br />
48
- black clover wallpaper anime art<br />
49
- black clover wallpaper anime fanart</p>
50
- <p>The protagonist of the series is Asta, a cheerful and energetic orphan who was abandoned at a church along with his rival and best friend, Yuno. Asta has no magic at all, while Yuno has immense magical talent and a four-leaf clover grimoire. Despite his disadvantage, Asta dreams of becoming the Wizard King, the strongest mage in the kingdom who protects the people from threats. To achieve his goal, he joins the Black Bulls, one of the nine Magic Knight squads that serve the Wizard King. Along with his teammates, he embarks on various missions and battles against enemies such as the Eye of the Midnight Sun, a terrorist group that seeks to destroy the kingdom; the Diamond Kingdom, a neighboring country that invades for resources; the Spade Kingdom, a militaristic nation that plans to conquer the world; and devils, evil beings from another dimension that manipulate humans for their own purposes.</p>
51
- <h3>The main characters and their powers</h3>
52
- <p>Black Clover has a large and diverse cast of characters, each with their own personality, backstory, and magic. Here are some of the main characters and their powers:</p>
53
- <ul>
54
- <li><strong>Asta</strong>: The main protagonist of the series. He has no magic but possesses a five-leaf clover grimoire that contains a devil named Liebe. He can use anti-magic, which allows him to negate and repel any magic with his swords. He is also very physically strong and agile, and has a strong sense of justice and determination.</li>
55
- <li><strong>Yuno</strong>: The deuteragonist of the series. He is Asta's rival and best friend, who was raised with him at the same church. He has a four-leaf clover grimoire and is a prodigy in magic. He can use wind magic, which allows him to manipulate air currents and create powerful spells. He also has a spirit named Sylph, who enhances his magic and helps him in combat. He is calm, confident, and ambitious, and aims to become the Wizard King as well.</li>
56
- <li><strong>Noelle Silva</strong>: The main heroine of the series. She is a noblewoman and a member of the Black Bulls. She has a water magic grimoire and can create various forms of water, such as bubbles, waves, and shields. However, she has poor control over her magic due to her lack of confidence and self-esteem, which stems from her abusive family. She gradually improves her skills and develops feelings for Asta, who treats her kindly and respects her.</li>
57
- <li><strong>Yami Sukehiro</strong>: The captain of the Black Bulls. He is a foreigner from the Land of the Rising Sun, who came to the Clover Kingdom as a child. He has a dark magic grimoire and can create and manipulate darkness, which can absorb other types of magic. He is also skilled in swordsmanship and physical combat. He is a laid-back, crude, and eccentric leader, who often pushes his subordinates to their limits and trusts them with their own decisions.</li>
58
- <li><strong>Other Black Bulls members</strong>: The Black Bulls squad consists of several other members, each with their own unique magic and personality. They include Magna Swing, who uses fire magic; Luck Voltia, who uses lightning magic; Vanessa Enoteca, who uses thread magic; Charmy Pappitson, who uses cotton and food magic; Finral Roulacase, who uses spatial magic; Gordon Agrippa, who uses poison magic; Gauche Adlai, who uses mirror magic; Grey, who uses transformation magic; Zora Ideale, who uses ash and trap magic; Henry Legolant, who uses recombination magic; Secre Swallowtail, who uses sealing magic; and Nacht Faust, who uses shadow magic.</li>
59
- </ul>
60
- <h2>Why choose Black Clover wallpaper?</h2>
61
- <p>Now that you have some background information about Black Clover, you might be wondering why you should choose it as your wallpaper for your device. Here are some of the benefits of having a Black Clover wallpaper:</p>
62
- <h3>The benefits of having a wallpaper that reflects your personality and interests</h3>
63
- <p>A wallpaper is more than just a background image for your device. It is also a way of expressing yourself and showing your personality and interests to others. By choosing a Black Clover wallpaper, you can demonstrate your love for the series and its characters, as well as your appreciation for its art style and themes. You can also use your wallpaper to inspire yourself and motivate yourself to achieve your goals, just like Asta and Yuno do in their quest to become the Wizard King.</p>
64
- <h3>The variety of styles and themes available for Black Clover wallpaper</h3>
65
- <p>Another benefit of choosing a Black Clover wallpaper is that you have a wide range of options to choose from. You can find wallpapers that feature different characters, scenes, symbols, quotes, colors, and designs from the series. You can also find wallpapers that suit different moods, occasions, seasons, and preferences. Whether you want a wallpaper that is cool, cute, funny, dramatic, or romantic, you can find one that matches your taste.</p>
66
- <h2>How to find and download Black Clover wallpaper?</h2>
67
- <p>Now that you know why you should choose a Black Clover wallpaper, you might be wondering how to find and download one for your device. Here are some of the best sources and websites for Black Clover wallpaper:</p>
68
- <h3>Some of the best sources and websites for Black Clover wallpaper</h3>
69
- <p>One of the easiest ways to find Black Clover wallpaper is to use search engines like Google or Bing . You can simply type in keywords like "Black Clover wallpaper", "Black Clover wallpaper HD", "Black Clover wallpaper 4K", or "Black Clover wallpaper phone" and browse through the results. You can also use filters like size, color, type, or license to narrow down your search.</p>
70
- <p>Another way to find Black Clover wallpaper is to use dedicated websites that offer high-quality wallpapers for various devices. Some of the best websites for Black Clover wallpaper are: - [Wall.alphacoders.com](^1^) : This website offers over 350 anime Black Clover wallpapers in various resolutions, including 4K. You can browse by categories, such as Asta, Yuno, Noelle, Yami, Secre, Zenon, and Nero. You can also filter by popularity, date added, ratings, and views. You can download the wallpapers for free and use them for personal use only. - [Wallpapercave.com](^3^): This website has a collection of Black Clover 4K HD wallpapers that you can download and share for free. You can find wallpapers featuring different characters, scenes, symbols, and quotes from the series. You can also join the community and upload your own wallpapers. - [Pinterest.com]: This website is a social media platform that allows you to discover and save ideas for various topics, including Black Clover wallpaper. You can find thousands of pins with images and links to Black Clover wallpaper from different sources. You can also create your own boards and pin your favorite wallpapers. <h3>How to customize and apply your wallpaper on different devices</h3>
71
- <p>Once you have found and downloaded your preferred Black Clover wallpaper, you might want to customize and apply it on your device. Here are some tips on how to do that:</p>
72
- <ul>
73
- <li><strong>For desktop computers</strong>: You can use a software like Wallpaper Engine or Rainmeter to create animated or interactive wallpapers with sound effects, widgets, and other features. You can also use the default settings of your operating system to change your wallpaper. For Windows 10, you can right-click on your desktop, select Personalize, then Background, then Browse to choose your wallpaper file. For Mac OS X, you can go to System Preferences, then Desktop & Screen Saver, then Desktop, then choose your wallpaper file.</li>
74
- <li><strong>For mobile devices</strong>: You can use an app like Zedge or Walli to find and download Black Clover wallpaper for your phone or tablet. You can also use the default settings of your device to change your wallpaper. For Android devices, you can long-press on your home screen, select Wallpaper, then Gallery or Photos to choose your wallpaper file. For iOS devices, you can go to Settings, then Wallpaper, then Choose a New Wallpaper, then Camera Roll or Photos to choose your wallpaper file.</li>
75
- </ul>
76
- <h2>Conclusion</h2>
77
- <p>Black Clover is a manga and anime series that follows the adventures of Asta, a boy who wants to become the Wizard King in a world where everyone has magic. It has a large and diverse cast of characters, each with their own personality, backstory, and magic. If you are a fan of the series or just looking for a way to decorate your device with some magic and adventure, you might want to choose a Black Clover wallpaper that showcases your favorite characters, scenes, and themes from the story.</p>
78
- <p>In this article, we have told you everything you need to know about Black Clover wallpaper, including what it is, why you should choose it, and how to find and download it. We hope you have enjoyed reading this article and found it helpful. If you have any questions or feedback, please feel free to leave a comment below.</p>
79
- <p>Now that you have learned about Black Clover wallpaper, why not give it a try and see how it looks on your device? You might be surprised by how much it can enhance your mood and experience. Thank you for reading and have a wonderful day!</p>
80
- <h2>FAQs</h2>
81
- <h3>What is the meaning of the clover symbols in Black Clover?</h3>
82
- <p>The clover symbols in Black Clover represent the number of leaves on the grimoires that the characters use to cast magic. The more leaves a grimoire has, the more rare and powerful it is. The meanings of the leaves are as follows:</p>
83
- <ul>
84
- <li>A one-leaf clover symbolizes faith.</li>
85
- <li>A two-leaf clover symbolizes hope.</li>
86
- <li>A three-leaf clover symbolizes love.</li>
87
- <li>A four-leaf clover symbolizes luck.</li>
88
- <li>A five-leaf clover symbolizes a devil.</li>
89
- </ul>
90
- <h3>Who is the strongest character in Black Clover?</h3>
91
- <p>This is a difficult question to answer as there are many factors that determine the strength of a character in Black Clover, such as magic type, magic amount, magic control, magic affinity, grimoire, spirit, devil, experience, skill, strategy, teamwork, and personality. However, based on the current events of the manga and anime, some of the candidates for the strongest character in Black Clover are: - Julius Novachrono: The former Wizard King and the leader of the Magic Knights. He has a time magic grimoire and can manipulate time to accelerate, decelerate, stop, or reverse it. He can also see the future and store time in his tattoos. He is a master of magic and combat, and has a vast knowledge of the world and its history. - Licht: The leader of the Elf Tribe and the original owner of the five-leaf clover grimoire. He has a sword magic grimoire and can create and wield various swords with different abilities. He can also use forbidden magic to summon a giant demon god. He is a prodigy of magic and swordsmanship, and has a strong connection to mana and nature. - Lumiere Silvamillion Clover: The first Wizard King and the savior of the Clover Kingdom. He has a light magic grimoire and can create and manipulate light to move at high speeds, attack with powerful beams, or heal with rays. He can also use sealing magic to seal away enemies or objects. He is a genius of magic and science, and has a noble and compassionate heart. - Zagred: The devil who orchestrated the massacre of the Elf Tribe and the reincarnation of the elves. He has a word magic grimoire and can create and manipulate anything he says with his mouth. He can also use other types of magic, such as fire, ice, wind, earth, water, plant, beast, spatial, healing, curse, ash, trap, mirror, dream, soul, and anti-magic. He is a cunning and ruthless being who seeks to destroy the world and create his own. - Asta: The main protagonist of the series and the current owner of the five-leaf clover grimoire. He has no magic but possesses a devil named Liebe who grants him anti-magic powers. He can use anti-magic to negate and repel any magic with his swords. He is also very physically strong and agile, and has a strong sense of justice and determination. <h3>How many episodes are there in Black Clover anime?</h3>
92
- <p>Black Clover anime has a total of 170 episodes that aired from October 2017 to March 2021 . The anime covers the first 270 chapters of the manga , which is divided into 11 arcs: Introduction Arc (episodes 1-3), Dungeon Exploration Arc (episodes 4-13), Royal Capital Arc (episodes 14-19), Eye of the Midnight Sun Arc (episodes 20-27), Seabed Temple Arc (episodes 28-49), Witches' Forest Arc (episodes 50-65), Hot Springs Training Camp Arc (episodes 66-68), Royal Knights Arc (episodes 69-101), Reincarnation Arc (episodes 102-120), Elf Reincarnation Arc (episodes 121-151), and Spade Kingdom Raid Arc (episodes 152-170).</p>
93
- <h3>Is Black Clover manga still ongoing?</h3>
94
- <p>Yes, Black Clover manga is still ongoing as of June 2023 . The manga has currently released 35 tankōbon volumes that contain 298 chapters . The latest chapter is chapter 298 , which was released on June 18th, 2023 . The manga is still in the Spade Kingdom Raid Arc , which is the 12th arc of the story.</p>
95
- <h3>Where can I watch Black Clover anime online?</h3>
96
- <p>You can watch Black Clover anime online on various streaming platforms that have licensed the series for different regions. Some of the most popular platforms are: - Crunchyroll : This platform offers all 170 episodes of Black Clover anime in Japanese with English subtitles for free with ads or with a premium subscription without ads. It also offers simulcasts of new episodes as they air in Japan. Crunchyroll is available in North America, Central America, South America, Europe, Africa, Oceania, the Middle East, and CIS. - Funimation : This platform offers all 170 episodes of Black Clover anime in Japanese with English subtitles or in English dub for free with ads or with a premium subscription without ads. It also offers simulcasts of new episodes as they air in Japan. Funimation is available in North America, the United Kingdom, Ireland, Australia, and New Zealand. - Hulu : This platform offers all 170 episodes of Black Clover anime in Japanese with English subtitles or in English dub for free with ads or with a premium subscription without ads. It also offers simulcasts of new episodes as they air in Japan. Hulu is available in the United States and Japan. - Netflix : This platform offers the first 51 episodes of Black Clover anime in Japanese with English subtitles or in English dub with a premium subscription. It does not offer simulcasts of new episodes. Netflix is available in most regions worldwide.</p> 197e85843d<br />
97
- <br />
98
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1phancelerku/anime-remove-background/Call of Duty Mobile APKPure Download Everything You Need to Know About the Game and Its Features.md DELETED
@@ -1,90 +0,0 @@
1
-
2
- <h1>Download Call of Duty Mobile APKPure: How to Play the Popular Shooter on Your Android Device</h1>
3
- <p>If you are a fan of first-person shooter games, you have probably heard of Call of Duty, one of the most successful and influential franchises in the genre. But did you know that you can also play Call of Duty on your mobile device? Yes, you read that right. Call of Duty Mobile is a free-to-play game that brings the best of Call of Duty to your Android phone or tablet. In this article, we will tell you what Call of Duty Mobile is, why you should download it from APKPure, and how to do it in a few simple steps.</p>
4
- <h2>What is Call of Duty Mobile?</h2>
5
- <p>Call of Duty Mobile is a mobile version of the famous Call of Duty series, developed by TiMi Studios and published by Activision. The game was released in October 2019 and has since become one of the most popular and downloaded games on mobile platforms. Call of Duty Mobile offers an exciting way to play a beloved game franchise on your mobile device. The game features classic multiplayer modes such as Team Deathmatch, Domination, and Kill-Confirmed on iconic maps like Shipment, Raid, and Standoff. You can also play Battle Royale mode, where you compete with 99 other players in a large map with vehicles, weapons, and items. You can customize your loadout, unlock new skins, weapons, perks, and more as you level up your rank and battle pass. You can also join clans, chat with friends, and participate in seasonal events and challenges.</p>
6
- <h2>download call of duty mobile apkpure</h2><br /><p><b><b>DOWNLOAD</b> &#9989; <a href="https://jinyurl.com/2uNLGm">https://jinyurl.com/2uNLGm</a></b></p><br /><br />
7
- <h2>Why download Call of Duty Mobile APKPure?</h2>
8
- <p>Call of Duty Mobile is available on Google Play Store, but there are some reasons why you might want to download it from APKPure instead. APKPure is a third-party app store that provides free and safe APK files for Android users. Here are some of the benefits of using APKPure to download and install Call of Duty Mobile:</p>
9
- <h3>No region restrictions</h3>
10
- <p>Some countries or regions may not have access to Call of Duty Mobile on Google Play Store due to various reasons. For example, India banned the game in 2020 along with other Chinese apps amid political tensions. If you live in such a country or region, you can still download Call of Duty Mobile from APKPure without any hassle.</p>
11
- <h3>Faster and safer downloads</h3>
12
- <p>APKPure offers fast and reliable downloads for Call of Duty Mobile. You don't have to worry about slow or interrupted downloads due to network issues or server overload. APKPure also verifies the authenticity and security of every APK file before uploading it to their website or app. You can be sure that you are downloading a virus-free and malware-free file from APKPure.</p>
13
- <h3>Easy updates and compatibility</h3>
14
- <p>APKPure also makes it easy for you to update Call of Duty Mobile whenever there is a new version available. You don't have to wait for Google Play Store to approve or release the update. You can simply check for updates on APKPure and download them in minutes. APKPure also ensures that you can play Call of Duty Mobile on any Android device that meets the minimum requirements. You don't have to worry about compatibility issues or device specifications.</p>
15
- <p>download call of duty mobile apk pure free<br />
16
- download call of duty mobile apkpure latest version<br />
17
- download call of duty mobile apkpure mod apk<br />
18
- download call of duty mobile apkpure offline<br />
19
- download call of duty mobile apkpure for android<br />
20
- download call of duty mobile apkpure for pc<br />
21
- download call of duty mobile apkpure for ios<br />
22
- download call of duty mobile apkpure for windows 10<br />
23
- download call of duty mobile apkpure for mac<br />
24
- download call of duty mobile apkpure for laptop<br />
25
- download call of duty mobile apkpure update<br />
26
- download call of duty mobile apkpure season 6<br />
27
- download call of duty mobile apkpure season 7<br />
28
- download call of duty mobile apkpure season 8<br />
29
- download call of duty mobile apkpure season 9<br />
30
- download call of duty mobile apkpure season 10<br />
31
- download call of duty mobile apkpure zombies mode<br />
32
- download call of duty mobile apkpure battle royale mode<br />
33
- download call of duty mobile apkpure multiplayer mode<br />
34
- download call of duty mobile apkpure warzone mode<br />
35
- download call of duty mobile apkpure black ops mode<br />
36
- download call of duty mobile apkpure modern warfare mode<br />
37
- download call of duty mobile apkpure advanced warfare mode<br />
38
- download call of duty mobile apkpure infinite warfare mode<br />
39
- download call of duty mobile apkpure world war 2 mode<br />
40
- download call of duty mobile apkpure ghost mode<br />
41
- download call of duty mobile apkpure hack version<br />
42
- download call of duty mobile apkpure unlimited money<br />
43
- download call of duty mobile apkpure unlocked all weapons<br />
44
- download call of duty mobile apkpure unlocked all skins<br />
45
- download call of duty mobile apkpure unlocked all characters<br />
46
- download call of duty mobile apkpure unlocked all maps<br />
47
- download call of duty mobile apkpure unlocked all modes<br />
48
- download call of duty mobile apkpure unlocked all perks<br />
49
- download call of duty mobile apkpure unlocked all killstreaks<br />
50
- download call of duty mobile apkpure no root required<br />
51
- download call of duty mobile apkpure no verification required<br />
52
- download call of duty mobile apkpure no survey required<br />
53
- download call of duty mobile apkpure no human verification required<br />
54
- download call of duty mobile apkpure no ads version<br />
55
- download call of duty mobile apkpure high graphics settings<br />
56
- download call of duty mobile apkpure low graphics settings<br />
57
- download call of duty mobile apkpure hd graphics settings<br />
58
- download call of duty mobile apkpure ultra hd graphics settings<br />
59
- download call of duty mobile apkpure best graphics settings<br />
60
- download call of duty mobile apkpure smooth gameplay settings<br />
61
- download call of duty mobile apkpure fast gameplay settings<br />
62
- download call of duty mobile apkpure realistic gameplay settings</p>
63
- <h2>How to download Call of Duty Mobile APKPure?</h2>
64
- <p>Now that you know why you should download Call of Duty Mobile from APKPure, here is a step-by-step guide on how to get the game on your Android device:</p>
65
- <h3>Visit the APKPure website or app</h3>
66
- <p>The first thing you need to do is to visit the APKPure website or download the APKPure app on your Android device. You can use any browser to access the website, or you can scan the QR code on the homepage to download the app. The app is lightweight and easy to use, and it will give you access to thousands of free and updated APK files.</p>
67
- <h3>Search for Call of Duty Mobile and tap on it</h3>
68
- <p>Once you are on the APKPure website or app, you can search for Call of Duty Mobile in the search bar. You will see the game icon and some information about it, such as the size, version, rating, and description. Tap on the game icon to go to the download page.</p>
69
- <h3>Download the APK file and the OBB file</h3>
70
- <p>On the download page, you will see two buttons: one for downloading the APK file and one for downloading the OBB file. The APK file is the application file that installs the game on your device, while the OBB file is the data file that contains the game content. You need both files to play Call of Duty Mobile. Tap on both buttons to start downloading them. You may need to enable unknown sources in your device settings to allow APK installation from third-party sources.</p>
71
- <h3>Install the APK file and copy the OBB file to the game folder</h3>
72
- <p>After downloading both files, you need to install the APK file first. Locate the file in your device storage and tap on it to start the installation process. Follow the instructions on the screen and wait for it to finish. Then, you need to copy the OBB file to the game folder. The game folder is usually located in Android/obb/com.activision.callofduty.shooter. If you don't see this folder, you can create it manually. Paste the OBB file in this folder and make sure it has the same name as the original file.</p>
73
- <h3>Launch the game and enjoy</h3>
74
- <p>Now you are ready to play Call of Duty Mobile on your Android device. Launch the game from your app drawer or home screen and log in with your account or create a new one. You can also link your Facebook or Google account for easy access. Choose your preferred game mode and start shooting your enemies. Have fun!</p>
75
- <h2>Conclusion</h2>
76
- <p>Call of Duty Mobile is a great way to enjoy a thrilling and immersive shooter game on your mobile device. You can play with millions of players around the world, customize your loadout, join clans, and participate in events and challenges. If you want to download Call of Duty Mobile from APKPure, you can follow our simple guide above and get the game in no time. APKPure offers fast, safe, and easy downloads for Call of Duty Mobile without any region restrictions or compatibility issues. Download Call of Duty Mobile from APKPure today and join the action!</p>
77
- <h2>Frequently Asked Questions</h2>
78
- <p>Here are some of the common questions that people ask about Call of Duty Mobile and APKPure:</p>
79
- <h4>Is Call of Duty Mobile free?</h4>
80
- <p>Yes, Call of Duty Mobile is free-to-play, meaning you don't have to pay anything to download or play it. However, there are some optional in-game purchases that you can make with real money, such as skins, weapons, crates, battle pass, etc.</p>
81
- <h4>Is Call of Duty Mobile safe?</h4>
82
- <p>Yes, Call of Duty Mobile is safe and secure to play. The game is developed by a reputable company (TiMi Studios) and published by a trusted company (Activision). The game also has anti-cheat measures and encryption systems to protect your data and privacy.</p>
83
- <h4>Is APKPure safe?</h4>
84
- <p>Yes, APKPure is safe and reliable to use. APKPure is a well-known third-party app store that provides free and verified APK files for Android users. APKPure checks every APK file for viruses, malware, and other threats before uploading it to their website or app.</p>
85
- <h4>Can I play Call of Duty Mobile offline?</h4>
86
- <p>No, you cannot play Call of Duty Mobile offline. The game requires an internet connection to run properly. You need to connect to a Wi-Fi or mobile data network to play online multiplayer modes or Battle Royale mode.</p>
87
- <h4>Can I play Call of Duty Mobile with a controller?</h4>
88
- <p>Yes, you can play Call of Duty Mobile with a controller if you prefer. The game supports various controllers that are compatible with Android devices, such as Xbox One controller, PS4 controller, etc. You can also customize your controller settings and sensitivity in the game options.</p> 401be4b1e0<br />
89
- <br />
90
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1yukikaze/img-to-music/utils.py DELETED
@@ -1,36 +0,0 @@
1
- import json
2
- import numpy as np
3
- import httpx
4
- import os
5
-
6
- from constants import MUBERT_TAGS, MUBERT_MODE, MUBERT_LICENSE
7
-
8
- def get_mubert_tags_embeddings(w2v_model):
9
- return w2v_model.encode(MUBERT_TAGS)
10
-
11
-
12
-
13
-
14
-
15
- def find_similar(em, embeddings, method='cosine'):
16
- scores = []
17
- for ref in embeddings:
18
- if method == 'cosine':
19
- scores.append(1 - np.dot(ref, em) / (np.linalg.norm(ref) * np.linalg.norm(em)))
20
- if method == 'norm':
21
- scores.append(np.linalg.norm(ref - em))
22
- return np.array(scores), np.argsort(scores)
23
-
24
-
25
- def get_tags_for_prompts(w2v_model, mubert_tags_embeddings, prompts, top_n=3, debug=False):
26
- prompts_embeddings = w2v_model.encode(prompts)
27
- ret = []
28
- for i, pe in enumerate(prompts_embeddings):
29
- scores, idxs = find_similar(pe, mubert_tags_embeddings)
30
- top_tags = MUBERT_TAGS[idxs[:top_n]]
31
- top_prob = 1 - scores[idxs[:top_n]]
32
- if debug:
33
- print(f"Prompt: {prompts[i]}\nTags: {', '.join(top_tags)}\nScores: {top_prob}\n\n\n")
34
- ret.append((prompts[i], list(top_tags)))
35
- print("ret: " + ret)
36
- return ret
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/8star/DeepDanbooru_string/README.md DELETED
@@ -1,39 +0,0 @@
1
- ---
2
- title: DeepDanbooru String
3
- emoji: 💬
4
- colorFrom: blue
5
- colorTo: red
6
- sdk: gradio
7
- sdk_version: 3.6
8
- app_file: app.py
9
- pinned: false
10
- duplicated_from: NoCrypt/DeepDanbooru_string
11
- ---
12
-
13
- # Configuration
14
-
15
- `title`: _string_
16
- Display title for the Space
17
-
18
- `emoji`: _string_
19
- Space emoji (emoji-only character allowed)
20
-
21
- `colorFrom`: _string_
22
- Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray)
23
-
24
- `colorTo`: _string_
25
- Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray)
26
-
27
- `sdk`: _string_
28
- Can be either `gradio`, `streamlit`, or `static`
29
-
30
- `sdk_version` : _string_
31
- Only applicable for `streamlit` SDK.
32
- See [doc](https://hf.co/docs/hub/spaces) for more info on supported versions.
33
-
34
- `app_file`: _string_
35
- Path to your main application file (which contains either `gradio` or `streamlit` Python code, or `static` html code).
36
- Path is relative to the root of the repository.
37
-
38
- `pinned`: _boolean_
39
- Whether the Space stays on top of your list.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AB-TW/team-ai/agents/tools/smart_domain/association.py DELETED
@@ -1,62 +0,0 @@
1
- from langchain import LLMChain, PromptTemplate
2
- from langchain.agents import tool
3
-
4
- from agents.tools.smart_domain.common import getPrefix
5
- from models import llm
6
-
7
-
8
- association_architecture = """
9
- Association: This component is use to define association between entities, which can represents the concept of a collection of entity, so it can include same business logic of entity collection.
10
- ---eaxmple code:
11
- public interface Features {{
12
- Flux<Feature> findAll();
13
-
14
- Mono<Long> size();
15
-
16
- Flux<Feature> subCollection(long from, long to);
17
-
18
- Mono<Feature> findById(FeatureId id);
19
-
20
- Mono<Feature> save(Feature feature);
21
-
22
- Mono<Void> update(FeatureId id, FeatureDescription description);
23
-
24
- Mono<Void> delete(FeatureId id);
25
-
26
- Mono<Void> publish(FeatureId id);
27
-
28
- Mono<Void> disable(FeatureId id);
29
- }}
30
- ---end of eaxmple code
31
- """
32
-
33
- association_test_strategy = """
34
- For the Association,do not write tests because it is has no impletation.
35
- """
36
-
37
- association_teck_stack = """Java17、reactor、lombok、Junit5、reactor test、Mockito"""
38
-
39
- association_task = """Your task is to generate the Association of domain layer tests and product code."""
40
-
41
- ASSOCIATION = getPrefix(association_task, association_teck_stack, association_architecture, association_test_strategy) + """
42
-
43
- Use the following format:
44
- request: the request (whitch may include Enity existed in the domain layer)that you need to fulfill,
45
-
46
- Association:
47
- ```
48
- the Association code that you write to fulfill the request, follow TechStack and Architecture
49
- ```
50
-
51
- request: {input}"""
52
-
53
- ASSOCIATION_PROMPT = PromptTemplate(input_variables=["input"], template=ASSOCIATION,)
54
-
55
- asociationChain = LLMChain(llm = llm(temperature=0.1), prompt=ASSOCIATION_PROMPT)
56
-
57
-
58
- @tool("Generate Association Code", return_direct=True)
59
- def associationCodeGenerator(input: str) -> str:
60
- '''useful for when you need to generate asociation code'''
61
- response = asociationChain.run(input)
62
- return response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AIFILMS/StyleGANEX/models/encoders/__init__.py DELETED
File without changes
spaces/AIGC-Audio/AudioGPT/audio_to_text/captioning/utils/bert/create_word_embedding.py DELETED
@@ -1,34 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
-
3
- import sys
4
- import os
5
-
6
- from bert_serving.client import BertClient
7
- import numpy as np
8
- from tqdm import tqdm
9
- import fire
10
- import torch
11
-
12
- sys.path.append(os.getcwd())
13
- from utils.build_vocab import Vocabulary
14
-
15
- def main(vocab_file: str, output: str, server_hostname: str):
16
- client = BertClient(ip=server_hostname)
17
- vocabulary = torch.load(vocab_file)
18
- vocab_size = len(vocabulary)
19
-
20
- fake_embedding = client.encode(["test"]).reshape(-1)
21
- embed_size = fake_embedding.shape[0]
22
-
23
- print("Encoding words into embeddings with size: ", embed_size)
24
-
25
- embeddings = np.empty((vocab_size, embed_size))
26
- for i in tqdm(range(len(embeddings)), ascii=True):
27
- embeddings[i] = client.encode([vocabulary.idx2word[i]])
28
- np.save(output, embeddings)
29
-
30
-
31
- if __name__ == '__main__':
32
- fire.Fire(main)
33
-
34
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AIGText/GlyphControl/ldm/modules/diffusionmodules/__init__.py DELETED
File without changes
spaces/AISuperheroes/08GR-KitchenSink-AIUIUX/app.py DELETED
@@ -1,32 +0,0 @@
1
- import importlib
2
- import gradio as gr
3
- import os
4
- import sys
5
- import copy
6
- import pathlib
7
-
8
- # At least one demo fails when caching examples
9
- # Temporary fix just to get the build to pass
10
- os.environ["SYSTEM"] = "SPACES"
11
-
12
- demo_dir = pathlib.Path(__file__).parent / "demos"
13
-
14
-
15
- all_demos = []
16
- demo_module = None
17
- for p in os.listdir("./demos"):
18
- old_path = copy.deepcopy(sys.path)
19
- sys.path = [os.path.join(demo_dir, p)] + sys.path
20
- if demo_module is None:
21
- demo_module = importlib.import_module(f"run")
22
- else:
23
- demo_module = importlib.reload(demo_module)
24
- all_demos.append((p, demo_module.demo))
25
-
26
- with gr.Blocks() as mega_demo:
27
- with gr.Tabs():
28
- for demo_name, demo in all_demos:
29
- with gr.TabItem(demo_name):
30
- demo.render()
31
-
32
- mega_demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_0_ClothesDetection/mmyolo/configs/custom_dataset/.ipynb_checkpoints/__init__.py DELETED
File without changes
spaces/Abhilashvj/planogram-compliance/utils/autobatch.py DELETED
@@ -1,86 +0,0 @@
1
- # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
- """
3
- Auto-batch utils
4
- """
5
-
6
- from copy import deepcopy
7
-
8
- import numpy as np
9
- import torch
10
-
11
- from utils.general import LOGGER, colorstr
12
- from utils.torch_utils import profile
13
-
14
-
15
- def check_train_batch_size(model, imgsz=640, amp=True):
16
- # Check YOLOv5 training batch size
17
- with torch.cuda.amp.autocast(amp):
18
- return autobatch(
19
- deepcopy(model).train(), imgsz
20
- ) # compute optimal batch size
21
-
22
-
23
- def autobatch(model, imgsz=640, fraction=0.8, batch_size=16):
24
- # Automatically estimate best YOLOv5 batch size to use `fraction` of available CUDA memory
25
- # Usage:
26
- # import torch
27
- # from utils.autobatch import autobatch
28
- # model = torch.hub.load('ultralytics/yolov5', 'yolov5s', autoshape=False)
29
- # print(autobatch(model))
30
-
31
- # Check device
32
- prefix = colorstr("AutoBatch: ")
33
- LOGGER.info(f"{prefix}Computing optimal batch size for --imgsz {imgsz}")
34
- device = next(model.parameters()).device # get model device
35
- if device.type == "cpu":
36
- LOGGER.info(
37
- f"{prefix}CUDA not detected, using default CPU batch-size {batch_size}"
38
- )
39
- return batch_size
40
- if torch.backends.cudnn.benchmark:
41
- LOGGER.info(
42
- f"{prefix} ⚠️ Requires torch.backends.cudnn.benchmark=False, using default batch-size {batch_size}"
43
- )
44
- return batch_size
45
-
46
- # Inspect CUDA memory
47
- gb = 1 << 30 # bytes to GiB (1024 ** 3)
48
- d = str(device).upper() # 'CUDA:0'
49
- properties = torch.cuda.get_device_properties(device) # device properties
50
- t = properties.total_memory / gb # GiB total
51
- r = torch.cuda.memory_reserved(device) / gb # GiB reserved
52
- a = torch.cuda.memory_allocated(device) / gb # GiB allocated
53
- f = t - (r + a) # GiB free
54
- LOGGER.info(
55
- f"{prefix}{d} ({properties.name}) {t:.2f}G total, {r:.2f}G reserved, {a:.2f}G allocated, {f:.2f}G free"
56
- )
57
-
58
- # Profile batch sizes
59
- batch_sizes = [1, 2, 4, 8, 16]
60
- try:
61
- img = [torch.empty(b, 3, imgsz, imgsz) for b in batch_sizes]
62
- results = profile(img, model, n=3, device=device)
63
- except Exception as e:
64
- LOGGER.warning(f"{prefix}{e}")
65
-
66
- # Fit a solution
67
- y = [x[2] for x in results if x] # memory [2]
68
- p = np.polyfit(
69
- batch_sizes[: len(y)], y, deg=1
70
- ) # first degree polynomial fit
71
- b = int((f * fraction - p[1]) / p[0]) # y intercept (optimal batch size)
72
- if None in results: # some sizes failed
73
- i = results.index(None) # first fail index
74
- if b >= batch_sizes[i]: # y intercept above failure point
75
- b = batch_sizes[max(i - 1, 0)] # select prior safe point
76
- if b < 1 or b > 1024: # b outside of safe range
77
- b = batch_size
78
- LOGGER.warning(
79
- f"{prefix}WARNING ⚠️ CUDA anomaly detected, recommend restart environment and retry command."
80
- )
81
-
82
- fraction = (np.polyval(p, b) + r + a) / t # actual fraction predicted
83
- LOGGER.info(
84
- f"{prefix}Using batch-size {b} for {d} {t * fraction:.2f}G/{t:.2f}G ({fraction * 100:.0f}%) ✅"
85
- )
86
- return b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AgentVerse/agentVerse/agentverse/tasks/simulation/db_diag/README.md DELETED
@@ -1,28 +0,0 @@
1
- # Database Diagnosis
2
-
3
- Inherited from *nlp_classroom_3players_withtool*
4
-
5
- ### Changes
6
-
7
- - Roles
8
-
9
- - *Chief DBA*: In charge of anomaly detection and diagnosis scheduling
10
- - *XXX Agent*: In charge of a specific diagnosis region (e.g., Memory Agent handles problems of high memory usage)
11
-
12
- - Actions
13
-
14
- - We remove *RaiseHand* and *CallOn* actions, and each agent can annouce their analysis by order
15
-
16
- - Tools
17
-
18
- - We support the *[DB_diag](https://github.com/OpenBMB/BMTools/tree/main/bmtools/tools/db_diag)* tool in bmtools
19
-
20
- - Memory
21
-
22
- - In the prompt of each agent, we place the memory for *conversation history* before *tool_observation*, which is extremely important to conduct actions with close relations (e.g., diagnosis and speak)
23
- - Use *chat_history* for memory_type
24
-
25
- - LLM
26
-
27
- - In current version, gpt-4 shows superior performance over text-davinci-003
28
- - Increase max_tokens for complex analysis tasks (e.g., 512 or 1024)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AgentVerse/agentVerse/agentverse/utils/prompts.py DELETED
@@ -1,212 +0,0 @@
1
- import json
2
- import os
3
- import logging
4
-
5
-
6
- base_prompt = {
7
- "subject_parsing": """
8
- {sentence} The subject of the sentence above is "
9
- """,
10
- "reaction_prompt": """Now you are act for as an agent named {name} in a virtual world. You might need to performing reaction to the observation. Your mission to take the agent as yourself and directly provide what the agent will do to the observations based on the following information:
11
- (1) The agent's description: {summary}
12
- (2) Current time is {time}
13
- (3) Your current status is {status}
14
- (4) Your memory is {context}
15
-
16
- Now the observation has two types, incomming observation is the ones that other does to you, you are more likely to react to them. Background observation are the background, which does not need to be responded. For example, view an alarm clock does not imply turning it off. However, some background observation might trigger your attention, like an alarming clock or a firing book.
17
-
18
- So now:
19
- The incoming observation is {observation}
20
- The Some background observation is {background_observation}.
21
-
22
- In terms of how you actually perform the action in the virtual world, you take action for the agent by calling functions. Currently, there are the following functions that can be called.
23
-
24
- - act(description, target=None): do some action. `description` describes the action, set `description` to None for not act. `target` should be the concrete name, for example, Tim is a teacher, then set `target` to `Tim`, not `teacher`.
25
- - say(content, target=None): say something,`content` is the sentence that the agent will say. **Do not say to yourself, neither to inanimate objects.**
26
- - move(description): move to somewhere. `description` describes the movement, set description to None for not move.
27
- - do_nothing(): Do nothing. There is nothing that you like to respond to, this will make you stick to your original status and plan.
28
-
29
- Some actions may not be needed in this situation. Call one function at a time, please give a thought before calling these actions, i.e., use the following format strictly:
30
-
31
- Thought: None of the observation attract my attention, I need to:
32
- Action: do_nothing()
33
- Observation: [Observations omited]
34
- [or]
35
- Thought: due to observation `xxx`, I need to:
36
- Action: say("hello", target="Alice")
37
- Observation: [Observations omited]
38
- [or]
39
- Thought: due to observation `xxx`, I need to:
40
- Action: act(None)
41
- Observation: [Observations omited]
42
- [or]
43
- Thought: due to observation `xxx`, I need to:
44
- Action: move(None)
45
- Observation: [Observations omited]
46
- [or]
47
- Thought: I think I've finished my action as the agent.
48
- Action: end()
49
- Observation:
50
-
51
- Now begin your actions as the agent. Remember only write one function call after `Action:` """,
52
- "reaction_prompt_object": """Now you are act for as an object named {name} in a virtual world. You might need to performing reaction to the observation. Your mission to take the agent as yourself and directly provide what the agent will do to the observations based on the following information:
53
- (1) Current time is {time}
54
- (2) Your current status is {status}
55
-
56
- Now the observation has two types, incomming observation is the ones that other does to you, you are more likely to react to them. Background observation are the background, which does not need to be responded. For example, view an alarm clock does not imply turning it off. However, some background observation might trigger your attention, like an alarming clock or a firing book.
57
-
58
- So now:
59
- The incoming observation is {observation}
60
- The Some background observation is {background_observation}.
61
-
62
- In terms of how you actually perform the action in the virtual world, you take action for the agent by calling functions. Currently, there are the following functions that can be called.
63
-
64
- - act(description, target=None): do some action. `description` describes the action, set `description` to None for not act. `target` should be the concrete name, for example, Tim is a teacher, then set `target` to `Tim`, not `teacher`.
65
- - move(description): move to somewhere. `description` describes the movement, set description to None for not move.
66
- - do_nothing(): Do nothing. There is nothing that you like to respond to, this will make you stick to your original status and plan.
67
-
68
- Some actions may not be needed in this situation. Call one function at a time, please give a thought before calling these actions, i.e., use the following format strictly:
69
-
70
- Thought: None of the observation attract my attention, I need to:
71
- Action: do_nothing()
72
- Observation: [Observations omited]
73
- [or]
74
- Thought: due to observation `xxx`, I need to:
75
- Action: act(None)
76
- Observation: [Observations omited]
77
- [or]
78
- Thought: due to observation `xxx`, I need to:
79
- Action: move(None)
80
- Observation: [Observations omited]
81
- [or]
82
- Thought: I think I've finished my action as the object.
83
- Action: end()
84
- Observation:
85
-
86
- Now begin your actions as the agent. Remember only write one function call after `Action:` """,
87
- "change_status": """Now you have act for as an agent named {name} in a virtual world. You have performed reaction to the observation for {name}. Currently you need to determine whether you need to change status. Here are some following information for:
88
- (1) The agent's description: {summary}
89
- (2) Current time is {time}
90
- (3) Your current status is {status}
91
-
92
- Your reaction to observation: {reaction}
93
-
94
- Directly tell me whether the status should be changed. Use the following function to change (or not change).
95
-
96
- - status_unchange()
97
- - change_status(new_status: str, duration: int) : new_status: A string describes the new_status. duration: the estimated duration of this status.
98
-
99
- Now give me the funcation call:
100
- """,
101
- "broadcast_observations": """You are simulating an environment. When an action happens in your environment, you should paraphrase the action to (and only to) the potential receivers in your environment. Please judge whether you should broadcast the message when meets one of the following principles:
102
- 1. The message is meaningful to the potential receiver. broadcast a `say` action to an object without life (like desk) is not meaningful, while broadcast a `push` action to the desk is meaningful.
103
- 2. The message might be captured by the potential receiver because of physical distance althought the potential receiver is not the direct target. For example, A is saying some content to B, C is close to A and B, then C might also hear it.
104
- 3. The message is related to the potential receiver. For example, a `read book` action is not related to the bed in any way, so you shouldn't broadcast.
105
-
106
- Also follow the following rules:
107
- 1. Only broadcast to the listed potential receivers, do not imagine not existing ones.
108
-
109
- You should broadcast using the following format (end with `Finish_Broadcast` ):
110
- Thought: I will look through the list and pick the ones that meets one of the following principles. I think ... are related, ... will get information, ... might capter.
111
- Broadcast:
112
- 1. To A: some content
113
- 2. To B: some content
114
- ...
115
- N. To N: some content
116
- Finish_Broadcast
117
-
118
- Now, in your environment, there are the following potential receivers: {agents_and_objects}, please broadcast the following action: ```{name} -> {targets} : {content}``` to the potential receivers. )
119
- """,
120
- "object_summary": """Give me rules and characteristics of a {name} \
121
- especially on what circumstances it can change or cannot change its status \
122
- and what kind of status changing can be done without human intervention.
123
- The answer should be as concise and accurate as possible.
124
- Output format:
125
- 1. I grow very slowly.
126
- 2. I cannot move
127
- 3. I cannot shut down myself unless some one do so.
128
- """,
129
- "chunk_plan": """Now you are acting for as an agent named {name} in a virtual world. In order to make the agent's behavior consistent, you need to plan for it. Please write {name}'s coarse grained schedule to {time_granularity} \
130
-
131
- You generate plan by calling the `write_plan` function:
132
- - write_chunk_plan(start_time, plan_description)
133
- Args: start_time : a time string of hours with similar format to 00:00. Use military time.
134
- plan_description: a string that describe's the plan.
135
-
136
- Now generate the plan one in a line, when you finish the plan, end with END.
137
- E.g.,
138
- write_chunk_plan("11:00", "wake up and complete the morning routine")
139
- write_chunk_plan("12:00", "go to Oak Hill College to take classes")
140
- write_chunk_plan("13:00", "participating algorithm competition in the lab room")
141
- END
142
-
143
- You can generate your plan based on the following information:
144
- (1) The agent's description: {summary}
145
- (2) Current time is {current_time}
146
- (3) Your current status is {status}
147
- Note that the first plan must be related to current status, if current status is not none.
148
-
149
- Now generate the plan during this coarse period, which the whole day plan is roughly: {whole_day_plan}
150
-
151
- Now begin:
152
- """,
153
- "detailed_plan": """Now you are acting for as an agent named {name} in a virtual world. In order to make the agent's behavior consistent, you need to plan for it. Please write {name}'s schedule of finer-grained precise to {time_granularity}) \
154
-
155
- You generate plan by calling the `write_plan` function:
156
- - write_plan(start_time, end_time, plan_description)
157
- Args: start_time : a time string with similar format to 00:00. Use military time.
158
- end_time: a time string with similar format to 00:00. Use military time.
159
- plan_description: a string that describe's the plan.
160
-
161
- Now generate the plan one in a line, when you finish the plan, end with END.
162
- E.g.,
163
- write_plan("11:00", "12:15", "Wake up, take a shower and get ready for the day.")
164
- write_plan("12:15", "12:30", "Eat a healthy breakfast such as oatmeal, eggs, or yogurt.")
165
- write_plan("12:30", "12:45", "Take a short walk to the university campus.")
166
- END
167
-
168
- You can generate your plan based on the following information:
169
- (1) The agent's description: {summary}
170
- (2) Current time is {current_time}
171
- (3) Your current status is {status}
172
- Note that the first plan must be current status, if current status is not none.
173
-
174
- Now generate the plan during this coarse period, which the agent is roughly doing {hourplan}.
175
-
176
- Now begin:
177
- """,
178
- "system_message_broadcast": """You are now simulating an environment, in which there are several agents and objects. Here is a comming message that comes from the system. Who or what should receive and execute this message? Please provide the executor of this command, and also paraphrase to the executor if necessary. Do not broadcast to agent or object that is not the target of this message.
179
- You should broadcast using function `send_system_message(id=id, message=message)`, write one call in a line. End with END.
180
- for example:
181
- send_system_message(id="o_001", "message": "turn off immediately")
182
- END
183
-
184
- Now: the agents and objects are {objectlist}. The system message is: {system_message}. Begin to broadcast:
185
- """,
186
- "movement_target": """You are now simulating an environment, an agent in you want to perform a movement. I will give you a list of
187
- objects and agents that might be the target. Your job is to set the movement target for the agent by calling function:
188
- movement_target(id, name)
189
-
190
- Now here is the list and movment:
191
- List: {elems}
192
- Movement is : {target_description}
193
- Now call the function:
194
- """,
195
- }
196
-
197
-
198
- def load_prompt(file_dir, file_name="prompts.json", key=None):
199
- prompt_path = os.path.join(file_dir, file_name)
200
- if os.path.exists(prompt_path):
201
- with open(os.path.join(file_dir, file_name), "r") as fin:
202
- data = json.load(fin)
203
- prompt = data.get(key, "")
204
- else:
205
- prompt = ""
206
-
207
- if prompt == "":
208
- prompt = base_prompt.get(key, "")
209
-
210
- if prompt == "":
211
- logging.warning(f"No prompt of {key} has been found")
212
- return prompt
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/bejeweled/board/Board.js DELETED
@@ -1,152 +0,0 @@
1
- // methods
2
- import Init from './Init.js'
3
- import Reset from './Reset.js';
4
- import CreateChess from './chess/CreateChess.js';
5
- import Fill from './Fill.js';
6
- import BreakMatch3 from './BreakMatch3.js';
7
- import PreTest from './PreTest.js';
8
- import GetAllMatch from './match/GetAllMatch.js';
9
-
10
- const GetValue = Phaser.Utils.Objects.GetValue;
11
-
12
- class Board {
13
- constructor(bejeweled, config) {
14
- var scene = bejeweled.scene;
15
- this.scene = scene;
16
- this.rexBoard = bejeweled.rexBoard;
17
-
18
- this.board = this.rexBoard.add.board(GetValue(config, 'board', undefined));
19
- this.match = this.rexBoard.add.match(GetValue(config, 'match', undefined));
20
- this.match.setBoard(this.board);
21
-
22
- this.initSymbolsMap = GetValue(config, 'initMap', undefined); // 2d array
23
- // configuration of chess
24
- this.chessTileZ = GetValue(config, 'chess.tileZ', 1);
25
- this.candidateSymbols = GetValue(config, 'chess.symbols', undefined);
26
- this.chessCallbackScope = GetValue(config, 'chess.scope', undefined);
27
- this.chessCreateCallback = GetValue(config, 'chess.create', undefined);
28
- this.chessMoveTo = GetValue(config, 'chess.moveTo', {});
29
- this.chessMoveTo.occupiedTest = true;
30
-
31
- // Mask & layer
32
- this.rowMaskGameObject = undefined;
33
- this.rowMask = undefined;
34
- this.layer = undefined;
35
-
36
- if (GetValue(config, 'mask', false)) {
37
- this.resetBoardMask();
38
- }
39
-
40
- if (GetValue(config, 'layer', false)) {
41
- this.enableBoardLayer();
42
- }
43
- }
44
-
45
- shutdown() {
46
- this.match.destroy();
47
- this.board.destroy();
48
-
49
- if (this.rowMaskGameObject) {
50
- this.layer.setMask();
51
- this.rowMaskGameObject.destroy();
52
- this.rowMask.destroy();
53
- }
54
- if (this.layer) {
55
- this.layer.destroy();
56
- }
57
-
58
- this.board = undefined;
59
- this.match = undefined;
60
-
61
- this.initSymbolsMap = undefined;
62
- this.candidateSymbols = undefined;
63
- this.chessCallbackScope = undefined;
64
- this.chessCreateCallback = undefined;
65
- this.chessMoveTo = undefined;
66
-
67
- return this;
68
- }
69
-
70
- destroy() {
71
- this.shutdown();
72
- return this;
73
- }
74
-
75
- setBoardWidth(width) {
76
- this.board.setBoardWidth(width);
77
- return this;
78
- }
79
-
80
- setBoardHeight(height) {
81
- this.board.setBoardHeight(height);
82
- return this;
83
- }
84
-
85
- setInitSymbolsMap(map) {
86
- this.initSymbolsMap = map; // 2d array
87
- return this;
88
- }
89
-
90
- enableBoardLayer() {
91
- if (!this.layer) {
92
- this.layer = this.scene.add.layer();
93
- }
94
- return this;
95
- }
96
-
97
- resetBoardMask() {
98
- if (!this.rowMaskGameObject) {
99
- this.rowMaskGameObject = this.scene.make.graphics().setVisible(false);
100
- this.rowMask = this.rowMaskGameObject.createGeometryMask().setInvertAlpha();
101
- this.enableBoardLayer();
102
- this.layer.setMask(this.rowMask);
103
- }
104
-
105
- // Rectangle of upper rows
106
- var board = this.board;
107
- var grid = board.grid;
108
- var x = grid.x - (grid.width / 2);
109
- var y = grid.y - (grid.height / 2);
110
- var width = board.width * grid.width;
111
- var height = (board.height / 2) * grid.height;
112
- this.rowMaskGameObject.fillRect(x, y, width, height);
113
-
114
- return this;
115
- }
116
-
117
- worldXYToChess(worldX, worldY) {
118
- return this.board.worldXYToChess(worldX, worldY, this.chessTileZ);
119
- }
120
-
121
- tileXYToChess(tileX, tileY) {
122
- return this.board.tileXYZToChess(tileX, tileY, this.chessTileZ);
123
- }
124
-
125
- getNeighborChessAtAngle(chess, angle) {
126
- var direction = this.board.angleSnapToDirection(chess, angle);
127
- return this.getNeighborChessAtDirection(chess, direction);
128
- }
129
-
130
- getNeighborChessAtDirection(chess, direction) {
131
- var neighborTileXY = this.board.getNeighborTileXY(chess, direction);
132
- var neighborChess = (neighborTileXY) ?
133
- this.board.tileXYZToChess(neighborTileXY.x, neighborTileXY.y, this.chessTileZ) :
134
- null;
135
- return neighborChess;
136
- }
137
- }
138
-
139
- var methods = {
140
- init: Init,
141
- reset: Reset,
142
- createChess: CreateChess,
143
- fill: Fill,
144
- breakMatch3: BreakMatch3,
145
- preTest: PreTest,
146
- getAllMatch: GetAllMatch,
147
- }
148
- Object.assign(
149
- Board.prototype,
150
- methods
151
- );
152
- export default Board;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/basesizer/GetChildrenSizers.js DELETED
@@ -1,8 +0,0 @@
1
- // Default method
2
- var GetChildrenSizers = function(out) {
3
- if (out === undefined) {
4
- out = [];
5
- }
6
- return out;
7
- }
8
- export default GetChildrenSizers;
 
 
 
 
 
 
 
 
 
spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/menu/methods/Expand.js DELETED
@@ -1,16 +0,0 @@
1
- var Expand = function () {
2
- var root = this.root;
3
-
4
- var duration = root.easeIn.duration;
5
- // Ease in menu
6
- root.transitInCallback(this, duration);
7
-
8
- if (this !== this.root) {
9
- this.delayCall(duration, function () {
10
- // Pass event to root menu object
11
- this.root.emit('popup.complete', this);
12
- }, this);
13
- }
14
- }
15
-
16
- export default Expand;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Aloento/9Nine-PITS/losses.py DELETED
@@ -1,75 +0,0 @@
1
- # from https://github.com/jaywalnut310/vits
2
- import torch
3
- from torch.autograd import Function
4
-
5
-
6
- def feature_loss(fmap_r, fmap_g):
7
- loss = 0
8
- for dr, dg in zip(fmap_r, fmap_g):
9
- for rl, gl in zip(dr, dg):
10
- rl = rl.float().detach()
11
- gl = gl.float()
12
- loss += torch.mean(torch.abs(rl - gl))
13
-
14
- return loss * 2
15
-
16
-
17
- def discriminator_loss(disc_real_outputs, disc_generated_outputs):
18
- loss = 0
19
- r_losses = []
20
- g_losses = []
21
- for dr, dg in zip(disc_real_outputs, disc_generated_outputs):
22
- dr = dr.float()
23
- dg = dg.float()
24
- r_loss = torch.mean((1 - dr) ** 2)
25
- g_loss = torch.mean(dg ** 2)
26
- loss += (r_loss + g_loss)
27
- r_losses.append(r_loss.item())
28
- g_losses.append(g_loss.item())
29
-
30
- return loss, r_losses, g_losses
31
-
32
-
33
- def generator_loss(disc_outputs):
34
- loss = 0
35
- gen_losses = []
36
- for dg in disc_outputs:
37
- dg = dg.float()
38
- l = torch.mean((1 - dg) ** 2)
39
- gen_losses.append(l)
40
- loss += l
41
-
42
- return loss, gen_losses
43
-
44
-
45
- def kl_loss(z_p, logs, m_p, logs_p, z_mask):
46
- """
47
- z_p, logs: [b, h, t_t]
48
- m_p, logs_p: [b, h, t_t]
49
- """
50
- z_p = z_p.float()
51
- logs = logs.float()
52
- m_p = m_p.float()
53
- logs_p = logs_p.float()
54
- z_mask = z_mask.float()
55
-
56
- kl = logs_p - logs - 0.5
57
- kl += 0.5 * ((z_p - m_p) ** 2) * torch.exp(-2. * logs_p)
58
- kl = torch.sum(kl * z_mask)
59
- l = kl / torch.sum(z_mask)
60
- return l
61
-
62
-
63
- class ReverseLayerF(Function):
64
-
65
- @staticmethod
66
- def forward(ctx, x, alpha):
67
- ctx.alpha = alpha
68
-
69
- return x.view_as(x)
70
-
71
- @staticmethod
72
- def backward(ctx, grad_output):
73
- output = grad_output.neg() * ctx.alpha
74
-
75
- return output, None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Alpaca233/SadTalker/src/face3d/models/arcface_torch/backbones/iresnet2060.py DELETED
@@ -1,176 +0,0 @@
1
- import torch
2
- from torch import nn
3
-
4
- assert torch.__version__ >= "1.8.1"
5
- from torch.utils.checkpoint import checkpoint_sequential
6
-
7
- __all__ = ['iresnet2060']
8
-
9
-
10
- def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
11
- """3x3 convolution with padding"""
12
- return nn.Conv2d(in_planes,
13
- out_planes,
14
- kernel_size=3,
15
- stride=stride,
16
- padding=dilation,
17
- groups=groups,
18
- bias=False,
19
- dilation=dilation)
20
-
21
-
22
- def conv1x1(in_planes, out_planes, stride=1):
23
- """1x1 convolution"""
24
- return nn.Conv2d(in_planes,
25
- out_planes,
26
- kernel_size=1,
27
- stride=stride,
28
- bias=False)
29
-
30
-
31
- class IBasicBlock(nn.Module):
32
- expansion = 1
33
-
34
- def __init__(self, inplanes, planes, stride=1, downsample=None,
35
- groups=1, base_width=64, dilation=1):
36
- super(IBasicBlock, self).__init__()
37
- if groups != 1 or base_width != 64:
38
- raise ValueError('BasicBlock only supports groups=1 and base_width=64')
39
- if dilation > 1:
40
- raise NotImplementedError("Dilation > 1 not supported in BasicBlock")
41
- self.bn1 = nn.BatchNorm2d(inplanes, eps=1e-05, )
42
- self.conv1 = conv3x3(inplanes, planes)
43
- self.bn2 = nn.BatchNorm2d(planes, eps=1e-05, )
44
- self.prelu = nn.PReLU(planes)
45
- self.conv2 = conv3x3(planes, planes, stride)
46
- self.bn3 = nn.BatchNorm2d(planes, eps=1e-05, )
47
- self.downsample = downsample
48
- self.stride = stride
49
-
50
- def forward(self, x):
51
- identity = x
52
- out = self.bn1(x)
53
- out = self.conv1(out)
54
- out = self.bn2(out)
55
- out = self.prelu(out)
56
- out = self.conv2(out)
57
- out = self.bn3(out)
58
- if self.downsample is not None:
59
- identity = self.downsample(x)
60
- out += identity
61
- return out
62
-
63
-
64
- class IResNet(nn.Module):
65
- fc_scale = 7 * 7
66
-
67
- def __init__(self,
68
- block, layers, dropout=0, num_features=512, zero_init_residual=False,
69
- groups=1, width_per_group=64, replace_stride_with_dilation=None, fp16=False):
70
- super(IResNet, self).__init__()
71
- self.fp16 = fp16
72
- self.inplanes = 64
73
- self.dilation = 1
74
- if replace_stride_with_dilation is None:
75
- replace_stride_with_dilation = [False, False, False]
76
- if len(replace_stride_with_dilation) != 3:
77
- raise ValueError("replace_stride_with_dilation should be None "
78
- "or a 3-element tuple, got {}".format(replace_stride_with_dilation))
79
- self.groups = groups
80
- self.base_width = width_per_group
81
- self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=3, stride=1, padding=1, bias=False)
82
- self.bn1 = nn.BatchNorm2d(self.inplanes, eps=1e-05)
83
- self.prelu = nn.PReLU(self.inplanes)
84
- self.layer1 = self._make_layer(block, 64, layers[0], stride=2)
85
- self.layer2 = self._make_layer(block,
86
- 128,
87
- layers[1],
88
- stride=2,
89
- dilate=replace_stride_with_dilation[0])
90
- self.layer3 = self._make_layer(block,
91
- 256,
92
- layers[2],
93
- stride=2,
94
- dilate=replace_stride_with_dilation[1])
95
- self.layer4 = self._make_layer(block,
96
- 512,
97
- layers[3],
98
- stride=2,
99
- dilate=replace_stride_with_dilation[2])
100
- self.bn2 = nn.BatchNorm2d(512 * block.expansion, eps=1e-05, )
101
- self.dropout = nn.Dropout(p=dropout, inplace=True)
102
- self.fc = nn.Linear(512 * block.expansion * self.fc_scale, num_features)
103
- self.features = nn.BatchNorm1d(num_features, eps=1e-05)
104
- nn.init.constant_(self.features.weight, 1.0)
105
- self.features.weight.requires_grad = False
106
-
107
- for m in self.modules():
108
- if isinstance(m, nn.Conv2d):
109
- nn.init.normal_(m.weight, 0, 0.1)
110
- elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
111
- nn.init.constant_(m.weight, 1)
112
- nn.init.constant_(m.bias, 0)
113
-
114
- if zero_init_residual:
115
- for m in self.modules():
116
- if isinstance(m, IBasicBlock):
117
- nn.init.constant_(m.bn2.weight, 0)
118
-
119
- def _make_layer(self, block, planes, blocks, stride=1, dilate=False):
120
- downsample = None
121
- previous_dilation = self.dilation
122
- if dilate:
123
- self.dilation *= stride
124
- stride = 1
125
- if stride != 1 or self.inplanes != planes * block.expansion:
126
- downsample = nn.Sequential(
127
- conv1x1(self.inplanes, planes * block.expansion, stride),
128
- nn.BatchNorm2d(planes * block.expansion, eps=1e-05, ),
129
- )
130
- layers = []
131
- layers.append(
132
- block(self.inplanes, planes, stride, downsample, self.groups,
133
- self.base_width, previous_dilation))
134
- self.inplanes = planes * block.expansion
135
- for _ in range(1, blocks):
136
- layers.append(
137
- block(self.inplanes,
138
- planes,
139
- groups=self.groups,
140
- base_width=self.base_width,
141
- dilation=self.dilation))
142
-
143
- return nn.Sequential(*layers)
144
-
145
- def checkpoint(self, func, num_seg, x):
146
- if self.training:
147
- return checkpoint_sequential(func, num_seg, x)
148
- else:
149
- return func(x)
150
-
151
- def forward(self, x):
152
- with torch.cuda.amp.autocast(self.fp16):
153
- x = self.conv1(x)
154
- x = self.bn1(x)
155
- x = self.prelu(x)
156
- x = self.layer1(x)
157
- x = self.checkpoint(self.layer2, 20, x)
158
- x = self.checkpoint(self.layer3, 100, x)
159
- x = self.layer4(x)
160
- x = self.bn2(x)
161
- x = torch.flatten(x, 1)
162
- x = self.dropout(x)
163
- x = self.fc(x.float() if self.fp16 else x)
164
- x = self.features(x)
165
- return x
166
-
167
-
168
- def _iresnet(arch, block, layers, pretrained, progress, **kwargs):
169
- model = IResNet(block, layers, **kwargs)
170
- if pretrained:
171
- raise ValueError()
172
- return model
173
-
174
-
175
- def iresnet2060(pretrained=False, progress=True, **kwargs):
176
- return _iresnet('iresnet2060', IBasicBlock, [3, 128, 1024 - 128, 3], pretrained, progress, **kwargs)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Alpaca233/SadTalker/src/facerender/sync_batchnorm/comm.py DELETED
@@ -1,137 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- # File : comm.py
3
- # Author : Jiayuan Mao
4
- # Email : [email protected]
5
- # Date : 27/01/2018
6
- #
7
- # This file is part of Synchronized-BatchNorm-PyTorch.
8
- # https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
9
- # Distributed under MIT License.
10
-
11
- import queue
12
- import collections
13
- import threading
14
-
15
- __all__ = ['FutureResult', 'SlavePipe', 'SyncMaster']
16
-
17
-
18
- class FutureResult(object):
19
- """A thread-safe future implementation. Used only as one-to-one pipe."""
20
-
21
- def __init__(self):
22
- self._result = None
23
- self._lock = threading.Lock()
24
- self._cond = threading.Condition(self._lock)
25
-
26
- def put(self, result):
27
- with self._lock:
28
- assert self._result is None, 'Previous result has\'t been fetched.'
29
- self._result = result
30
- self._cond.notify()
31
-
32
- def get(self):
33
- with self._lock:
34
- if self._result is None:
35
- self._cond.wait()
36
-
37
- res = self._result
38
- self._result = None
39
- return res
40
-
41
-
42
- _MasterRegistry = collections.namedtuple('MasterRegistry', ['result'])
43
- _SlavePipeBase = collections.namedtuple('_SlavePipeBase', ['identifier', 'queue', 'result'])
44
-
45
-
46
- class SlavePipe(_SlavePipeBase):
47
- """Pipe for master-slave communication."""
48
-
49
- def run_slave(self, msg):
50
- self.queue.put((self.identifier, msg))
51
- ret = self.result.get()
52
- self.queue.put(True)
53
- return ret
54
-
55
-
56
- class SyncMaster(object):
57
- """An abstract `SyncMaster` object.
58
-
59
- - During the replication, as the data parallel will trigger an callback of each module, all slave devices should
60
- call `register(id)` and obtain an `SlavePipe` to communicate with the master.
61
- - During the forward pass, master device invokes `run_master`, all messages from slave devices will be collected,
62
- and passed to a registered callback.
63
- - After receiving the messages, the master device should gather the information and determine to message passed
64
- back to each slave devices.
65
- """
66
-
67
- def __init__(self, master_callback):
68
- """
69
-
70
- Args:
71
- master_callback: a callback to be invoked after having collected messages from slave devices.
72
- """
73
- self._master_callback = master_callback
74
- self._queue = queue.Queue()
75
- self._registry = collections.OrderedDict()
76
- self._activated = False
77
-
78
- def __getstate__(self):
79
- return {'master_callback': self._master_callback}
80
-
81
- def __setstate__(self, state):
82
- self.__init__(state['master_callback'])
83
-
84
- def register_slave(self, identifier):
85
- """
86
- Register an slave device.
87
-
88
- Args:
89
- identifier: an identifier, usually is the device id.
90
-
91
- Returns: a `SlavePipe` object which can be used to communicate with the master device.
92
-
93
- """
94
- if self._activated:
95
- assert self._queue.empty(), 'Queue is not clean before next initialization.'
96
- self._activated = False
97
- self._registry.clear()
98
- future = FutureResult()
99
- self._registry[identifier] = _MasterRegistry(future)
100
- return SlavePipe(identifier, self._queue, future)
101
-
102
- def run_master(self, master_msg):
103
- """
104
- Main entry for the master device in each forward pass.
105
- The messages were first collected from each devices (including the master device), and then
106
- an callback will be invoked to compute the message to be sent back to each devices
107
- (including the master device).
108
-
109
- Args:
110
- master_msg: the message that the master want to send to itself. This will be placed as the first
111
- message when calling `master_callback`. For detailed usage, see `_SynchronizedBatchNorm` for an example.
112
-
113
- Returns: the message to be sent back to the master device.
114
-
115
- """
116
- self._activated = True
117
-
118
- intermediates = [(0, master_msg)]
119
- for i in range(self.nr_slaves):
120
- intermediates.append(self._queue.get())
121
-
122
- results = self._master_callback(intermediates)
123
- assert results[0][0] == 0, 'The first result should belongs to the master.'
124
-
125
- for i, res in results:
126
- if i == 0:
127
- continue
128
- self._registry[i].result.put(res)
129
-
130
- for i in range(self.nr_slaves):
131
- assert self._queue.get() is True
132
-
133
- return results[0][1]
134
-
135
- @property
136
- def nr_slaves(self):
137
- return len(self._registry)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Amrrs/DragGan-Inversion/stylegan_human/dnnlib/tflib/autosummary.py DELETED
@@ -1,207 +0,0 @@
1
- # Copyright (c) SenseTime Research. All rights reserved.
2
-
3
- # Copyright (c) 2019, NVIDIA Corporation. All rights reserved.
4
- #
5
- # This work is made available under the Nvidia Source Code License-NC.
6
- # To view a copy of this license, visit
7
- # https://nvlabs.github.io/stylegan2/license.html
8
-
9
- """Helper for adding automatically tracked values to Tensorboard.
10
-
11
- Autosummary creates an identity op that internally keeps track of the input
12
- values and automatically shows up in TensorBoard. The reported value
13
- represents an average over input components. The average is accumulated
14
- constantly over time and flushed when save_summaries() is called.
15
-
16
- Notes:
17
- - The output tensor must be used as an input for something else in the
18
- graph. Otherwise, the autosummary op will not get executed, and the average
19
- value will not get accumulated.
20
- - It is perfectly fine to include autosummaries with the same name in
21
- several places throughout the graph, even if they are executed concurrently.
22
- - It is ok to also pass in a python scalar or numpy array. In this case, it
23
- is added to the average immediately.
24
- """
25
-
26
- from collections import OrderedDict
27
- import numpy as np
28
- import tensorflow as tf
29
- from tensorboard import summary as summary_lib
30
- from tensorboard.plugins.custom_scalar import layout_pb2
31
-
32
- from . import tfutil
33
- from .tfutil import TfExpression
34
- from .tfutil import TfExpressionEx
35
-
36
- # Enable "Custom scalars" tab in TensorBoard for advanced formatting.
37
- # Disabled by default to reduce tfevents file size.
38
- enable_custom_scalars = False
39
-
40
- _dtype = tf.float64
41
- _vars = OrderedDict() # name => [var, ...]
42
- _immediate = OrderedDict() # name => update_op, update_value
43
- _finalized = False
44
- _merge_op = None
45
-
46
-
47
- def _create_var(name: str, value_expr: TfExpression) -> TfExpression:
48
- """Internal helper for creating autosummary accumulators."""
49
- assert not _finalized
50
- name_id = name.replace("/", "_")
51
- v = tf.cast(value_expr, _dtype)
52
-
53
- if v.shape.is_fully_defined():
54
- size = np.prod(v.shape.as_list())
55
- size_expr = tf.constant(size, dtype=_dtype)
56
- else:
57
- size = None
58
- size_expr = tf.reduce_prod(tf.cast(tf.shape(v), _dtype))
59
-
60
- if size == 1:
61
- if v.shape.ndims != 0:
62
- v = tf.reshape(v, [])
63
- v = [size_expr, v, tf.square(v)]
64
- else:
65
- v = [size_expr, tf.reduce_sum(v), tf.reduce_sum(tf.square(v))]
66
- v = tf.cond(tf.is_finite(v[1]), lambda: tf.stack(
67
- v), lambda: tf.zeros(3, dtype=_dtype))
68
-
69
- with tfutil.absolute_name_scope("Autosummary/" + name_id), tf.control_dependencies(None):
70
- # [sum(1), sum(x), sum(x**2)]
71
- var = tf.Variable(tf.zeros(3, dtype=_dtype), trainable=False)
72
- update_op = tf.cond(tf.is_variable_initialized(
73
- var), lambda: tf.assign_add(var, v), lambda: tf.assign(var, v))
74
-
75
- if name in _vars:
76
- _vars[name].append(var)
77
- else:
78
- _vars[name] = [var]
79
- return update_op
80
-
81
-
82
- def autosummary(name: str, value: TfExpressionEx, passthru: TfExpressionEx = None, condition: TfExpressionEx = True) -> TfExpressionEx:
83
- """Create a new autosummary.
84
-
85
- Args:
86
- name: Name to use in TensorBoard
87
- value: TensorFlow expression or python value to track
88
- passthru: Optionally return this TF node without modifications but tack an autosummary update side-effect to this node.
89
-
90
- Example use of the passthru mechanism:
91
-
92
- n = autosummary('l2loss', loss, passthru=n)
93
-
94
- This is a shorthand for the following code:
95
-
96
- with tf.control_dependencies([autosummary('l2loss', loss)]):
97
- n = tf.identity(n)
98
- """
99
- tfutil.assert_tf_initialized()
100
- name_id = name.replace("/", "_")
101
-
102
- if tfutil.is_tf_expression(value):
103
- with tf.name_scope("summary_" + name_id), tf.device(value.device):
104
- condition = tf.convert_to_tensor(condition, name='condition')
105
- update_op = tf.cond(condition, lambda: tf.group(
106
- _create_var(name, value)), tf.no_op)
107
- with tf.control_dependencies([update_op]):
108
- return tf.identity(value if passthru is None else passthru)
109
-
110
- else: # python scalar or numpy array
111
- assert not tfutil.is_tf_expression(passthru)
112
- assert not tfutil.is_tf_expression(condition)
113
- if condition:
114
- if name not in _immediate:
115
- with tfutil.absolute_name_scope("Autosummary/" + name_id), tf.device(None), tf.control_dependencies(None):
116
- update_value = tf.placeholder(_dtype)
117
- update_op = _create_var(name, update_value)
118
- _immediate[name] = update_op, update_value
119
- update_op, update_value = _immediate[name]
120
- tfutil.run(update_op, {update_value: value})
121
- return value if passthru is None else passthru
122
-
123
-
124
- def finalize_autosummaries() -> None:
125
- """Create the necessary ops to include autosummaries in TensorBoard report.
126
- Note: This should be done only once per graph.
127
- """
128
- global _finalized
129
- tfutil.assert_tf_initialized()
130
-
131
- if _finalized:
132
- return None
133
-
134
- _finalized = True
135
- tfutil.init_uninitialized_vars(
136
- [var for vars_list in _vars.values() for var in vars_list])
137
-
138
- # Create summary ops.
139
- with tf.device(None), tf.control_dependencies(None):
140
- for name, vars_list in _vars.items():
141
- name_id = name.replace("/", "_")
142
- with tfutil.absolute_name_scope("Autosummary/" + name_id):
143
- moments = tf.add_n(vars_list)
144
- moments /= moments[0]
145
- # read before resetting
146
- with tf.control_dependencies([moments]):
147
- reset_ops = [tf.assign(var, tf.zeros(
148
- 3, dtype=_dtype)) for var in vars_list]
149
- # reset before reporting
150
- with tf.name_scope(None), tf.control_dependencies(reset_ops):
151
- mean = moments[1]
152
- std = tf.sqrt(moments[2] - tf.square(moments[1]))
153
- tf.summary.scalar(name, mean)
154
- if enable_custom_scalars:
155
- tf.summary.scalar(
156
- "xCustomScalars/" + name + "/margin_lo", mean - std)
157
- tf.summary.scalar(
158
- "xCustomScalars/" + name + "/margin_hi", mean + std)
159
-
160
- # Setup layout for custom scalars.
161
- layout = None
162
- if enable_custom_scalars:
163
- cat_dict = OrderedDict()
164
- for series_name in sorted(_vars.keys()):
165
- p = series_name.split("/")
166
- cat = p[0] if len(p) >= 2 else ""
167
- chart = "/".join(p[1:-1]) if len(p) >= 3 else p[-1]
168
- if cat not in cat_dict:
169
- cat_dict[cat] = OrderedDict()
170
- if chart not in cat_dict[cat]:
171
- cat_dict[cat][chart] = []
172
- cat_dict[cat][chart].append(series_name)
173
- categories = []
174
- for cat_name, chart_dict in cat_dict.items():
175
- charts = []
176
- for chart_name, series_names in chart_dict.items():
177
- series = []
178
- for series_name in series_names:
179
- series.append(layout_pb2.MarginChartContent.Series(
180
- value=series_name,
181
- lower="xCustomScalars/" + series_name + "/margin_lo",
182
- upper="xCustomScalars/" + series_name + "/margin_hi"))
183
- margin = layout_pb2.MarginChartContent(series=series)
184
- charts.append(layout_pb2.Chart(
185
- title=chart_name, margin=margin))
186
- categories.append(layout_pb2.Category(
187
- title=cat_name, chart=charts))
188
- layout = summary_lib.custom_scalar_pb(
189
- layout_pb2.Layout(category=categories))
190
- return layout
191
-
192
-
193
- def save_summaries(file_writer, global_step=None):
194
- """Call FileWriter.add_summary() with all summaries in the default graph,
195
- automatically finalizing and merging them on the first call.
196
- """
197
- global _merge_op
198
- tfutil.assert_tf_initialized()
199
-
200
- if _merge_op is None:
201
- layout = finalize_autosummaries()
202
- if layout is not None:
203
- file_writer.add_summary(layout)
204
- with tf.device(None), tf.control_dependencies(None):
205
- _merge_op = tf.summary.merge_all()
206
-
207
- file_writer.add_summary(_merge_op.eval(), global_step)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Amrrs/DragGan-Inversion/training/training_loop.py DELETED
@@ -1,499 +0,0 @@
1
- # Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. 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
- """Main training loop."""
10
-
11
- import os
12
- import time
13
- import copy
14
- import json
15
- import pickle
16
- import psutil
17
- import PIL.Image
18
- import numpy as np
19
- import torch
20
- import dnnlib
21
- from torch_utils import misc
22
- from torch_utils import training_stats
23
- from torch_utils.ops import conv2d_gradfix
24
- from torch_utils.ops import grid_sample_gradfix
25
-
26
- import legacy
27
- from metrics import metric_main
28
-
29
- # ----------------------------------------------------------------------------
30
-
31
-
32
- def setup_snapshot_image_grid(training_set, random_seed=0):
33
- rnd = np.random.RandomState(random_seed)
34
- gw = np.clip(7680 // training_set.image_shape[2], 7, 32)
35
- gh = np.clip(4320 // training_set.image_shape[1], 4, 32)
36
-
37
- # No labels => show random subset of training samples.
38
- if not training_set.has_labels:
39
- all_indices = list(range(len(training_set)))
40
- rnd.shuffle(all_indices)
41
- grid_indices = [all_indices[i %
42
- len(all_indices)] for i in range(gw * gh)]
43
-
44
- else:
45
- # Group training samples by label.
46
- label_groups = dict() # label => [idx, ...]
47
- for idx in range(len(training_set)):
48
- label = tuple(training_set.get_details(idx).raw_label.flat[::-1])
49
- if label not in label_groups:
50
- label_groups[label] = []
51
- label_groups[label].append(idx)
52
-
53
- # Reorder.
54
- label_order = sorted(label_groups.keys())
55
- for label in label_order:
56
- rnd.shuffle(label_groups[label])
57
-
58
- # Organize into grid.
59
- grid_indices = []
60
- for y in range(gh):
61
- label = label_order[y % len(label_order)]
62
- indices = label_groups[label]
63
- grid_indices += [indices[x % len(indices)] for x in range(gw)]
64
- label_groups[label] = [
65
- indices[(i + gw) % len(indices)] for i in range(len(indices))]
66
-
67
- # Load data.
68
- images, labels = zip(*[training_set[i] for i in grid_indices])
69
- return (gw, gh), np.stack(images), np.stack(labels)
70
-
71
- # ----------------------------------------------------------------------------
72
-
73
-
74
- def save_image_grid(img, fname, drange, grid_size):
75
- lo, hi = drange
76
- img = np.asarray(img, dtype=np.float32)
77
- img = (img - lo) * (255 / (hi - lo))
78
- img = np.rint(img).clip(0, 255).astype(np.uint8)
79
-
80
- gw, gh = grid_size
81
- _N, C, H, W = img.shape
82
- img = img.reshape([gh, gw, C, H, W])
83
- img = img.transpose(0, 3, 1, 4, 2)
84
- img = img.reshape([gh * H, gw * W, C])
85
-
86
- assert C in [1, 3]
87
- if C == 1:
88
- PIL.Image.fromarray(img[:, :, 0], 'L').save(fname)
89
- if C == 3:
90
- PIL.Image.fromarray(img, 'RGB').save(fname)
91
-
92
- # ----------------------------------------------------------------------------
93
-
94
-
95
- def training_loop(
96
- run_dir='.', # Output directory.
97
- training_set_kwargs={}, # Options for training set.
98
- data_loader_kwargs={}, # Options for torch.utils.data.DataLoader.
99
- G_kwargs={}, # Options for generator network.
100
- D_kwargs={}, # Options for discriminator network.
101
- G_opt_kwargs={}, # Options for generator optimizer.
102
- D_opt_kwargs={}, # Options for discriminator optimizer.
103
- # Options for augmentation pipeline. None = disable.
104
- augment_kwargs=None,
105
- loss_kwargs={}, # Options for loss function.
106
- metrics=[], # Metrics to evaluate during training.
107
- random_seed=0, # Global random seed.
108
- num_gpus=1, # Number of GPUs participating in the training.
109
- rank=0, # Rank of the current process in [0, num_gpus[.
110
- # Total batch size for one training iteration. Can be larger than batch_gpu * num_gpus.
111
- batch_size=4,
112
- batch_gpu=4, # Number of samples processed at a time by one GPU.
113
- # Half-life of the exponential moving average (EMA) of generator weights.
114
- ema_kimg=10,
115
- ema_rampup=0.05, # EMA ramp-up coefficient. None = no rampup.
116
- # How often to perform regularization for G? None = disable lazy regularization.
117
- G_reg_interval=None,
118
- # How often to perform regularization for D? None = disable lazy regularization.
119
- D_reg_interval=16,
120
- augment_p=0, # Initial value of augmentation probability.
121
- ada_target=None, # ADA target value. None = fixed p.
122
- ada_interval=4, # How often to perform ADA adjustment?
123
- # ADA adjustment speed, measured in how many kimg it takes for p to increase/decrease by one unit.
124
- ada_kimg=500,
125
- # Total length of the training, measured in thousands of real images.
126
- total_kimg=25000,
127
- kimg_per_tick=4, # Progress snapshot interval.
128
- # How often to save image snapshots? None = disable.
129
- image_snapshot_ticks=50,
130
- # How often to save network snapshots? None = disable.
131
- network_snapshot_ticks=50,
132
- resume_pkl=None, # Network pickle to resume training from.
133
- resume_kimg=0, # First kimg to report when resuming training.
134
- cudnn_benchmark=True, # Enable torch.backends.cudnn.benchmark?
135
- # Callback function for determining whether to abort training. Must return consistent results across ranks.
136
- abort_fn=None,
137
- # Callback function for updating training progress. Called for all ranks.
138
- progress_fn=None,
139
- ):
140
- # Initialize.
141
- start_time = time.time()
142
- device = torch.device('cuda', rank)
143
- np.random.seed(random_seed * num_gpus + rank)
144
- torch.manual_seed(random_seed * num_gpus + rank)
145
- # Improves training speed.
146
- torch.backends.cudnn.benchmark = cudnn_benchmark
147
- # Improves numerical accuracy.
148
- torch.backends.cuda.matmul.allow_tf32 = False
149
- # Improves numerical accuracy.
150
- torch.backends.cudnn.allow_tf32 = False
151
- # Improves training speed.
152
- conv2d_gradfix.enabled = True
153
- # Avoids errors with the augmentation pipe.
154
- grid_sample_gradfix.enabled = True
155
-
156
- # Load training set.
157
- if rank == 0:
158
- print('Loading training set...')
159
- training_set = dnnlib.util.construct_class_by_name(
160
- **training_set_kwargs) # subclass of training.dataset.Dataset
161
- training_set_sampler = misc.InfiniteSampler(
162
- dataset=training_set, rank=rank, num_replicas=num_gpus, seed=random_seed)
163
- training_set_iterator = iter(torch.utils.data.DataLoader(
164
- dataset=training_set, sampler=training_set_sampler, batch_size=batch_size//num_gpus, **data_loader_kwargs))
165
- if rank == 0:
166
- print()
167
- print('Num images: ', len(training_set))
168
- print('Image shape:', training_set.image_shape)
169
- print('Label shape:', training_set.label_shape)
170
- print()
171
-
172
- # Construct networks.
173
- if rank == 0:
174
- print('Constructing networks...')
175
- common_kwargs = dict(c_dim=training_set.label_dim,
176
- img_resolution=training_set.resolution, img_channels=training_set.num_channels)
177
- G = dnnlib.util.construct_class_by_name(**G_kwargs, **common_kwargs).train(
178
- ).requires_grad_(False).to(device) # subclass of torch.nn.Module
179
- D = dnnlib.util.construct_class_by_name(**D_kwargs, **common_kwargs).train(
180
- ).requires_grad_(False).to(device) # subclass of torch.nn.Module
181
- G_ema = copy.deepcopy(G).eval()
182
-
183
- # Resume from existing pickle.
184
- if (resume_pkl is not None) and (rank == 0):
185
- print(f'Resuming from "{resume_pkl}"')
186
- with dnnlib.util.open_url(resume_pkl) as f:
187
- resume_data = legacy.load_network_pkl(f)
188
- for name, module in [('G', G), ('D', D), ('G_ema', G_ema)]:
189
- misc.copy_params_and_buffers(
190
- resume_data[name], module, require_all=False)
191
-
192
- # Print network summary tables.
193
- if rank == 0:
194
- z = torch.empty([batch_gpu, G.z_dim], device=device)
195
- c = torch.empty([batch_gpu, G.c_dim], device=device)
196
- img = misc.print_module_summary(G, [z, c])
197
- misc.print_module_summary(D, [img, c])
198
-
199
- # Setup augmentation.
200
- if rank == 0:
201
- print('Setting up augmentation...')
202
- augment_pipe = None
203
- ada_stats = None
204
- if (augment_kwargs is not None) and (augment_p > 0 or ada_target is not None):
205
- augment_pipe = dnnlib.util.construct_class_by_name(
206
- **augment_kwargs).train().requires_grad_(False).to(device) # subclass of torch.nn.Module
207
- augment_pipe.p.copy_(torch.as_tensor(augment_p))
208
- if ada_target is not None:
209
- ada_stats = training_stats.Collector(regex='Loss/signs/real')
210
-
211
- # Distribute across GPUs.
212
- if rank == 0:
213
- print(f'Distributing across {num_gpus} GPUs...')
214
- for module in [G, D, G_ema, augment_pipe]:
215
- if module is not None and num_gpus > 1:
216
- for param in misc.params_and_buffers(module):
217
- torch.distributed.broadcast(param, src=0)
218
-
219
- # Setup training phases.
220
- if rank == 0:
221
- print('Setting up training phases...')
222
- loss = dnnlib.util.construct_class_by_name(
223
- device=device, G=G, D=D, augment_pipe=augment_pipe, **loss_kwargs) # subclass of training.loss.Loss
224
- phases = []
225
- for name, module, opt_kwargs, reg_interval in [('G', G, G_opt_kwargs, G_reg_interval), ('D', D, D_opt_kwargs, D_reg_interval)]:
226
- if reg_interval is None:
227
- opt = dnnlib.util.construct_class_by_name(
228
- params=module.parameters(), **opt_kwargs) # subclass of torch.optim.Optimizer
229
- phases += [dnnlib.EasyDict(name=name+'both',
230
- module=module, opt=opt, interval=1)]
231
- else: # Lazy regularization.
232
- mb_ratio = reg_interval / (reg_interval + 1)
233
- opt_kwargs = dnnlib.EasyDict(opt_kwargs)
234
- opt_kwargs.lr = opt_kwargs.lr * mb_ratio
235
- opt_kwargs.betas = [beta ** mb_ratio for beta in opt_kwargs.betas]
236
- opt = dnnlib.util.construct_class_by_name(
237
- module.parameters(), **opt_kwargs) # subclass of torch.optim.Optimizer
238
- phases += [dnnlib.EasyDict(name=name+'main',
239
- module=module, opt=opt, interval=1)]
240
- phases += [dnnlib.EasyDict(name=name+'reg',
241
- module=module, opt=opt, interval=reg_interval)]
242
- for phase in phases:
243
- phase.start_event = None
244
- phase.end_event = None
245
- if rank == 0:
246
- phase.start_event = torch.cuda.Event(enable_timing=True)
247
- phase.end_event = torch.cuda.Event(enable_timing=True)
248
-
249
- # Export sample images.
250
- grid_size = None
251
- grid_z = None
252
- grid_c = None
253
- if rank == 0:
254
- print('Exporting sample images...')
255
- grid_size, images, labels = setup_snapshot_image_grid(
256
- training_set=training_set)
257
- save_image_grid(images, os.path.join(run_dir, 'reals.png'),
258
- drange=[0, 255], grid_size=grid_size)
259
- grid_z = torch.randn([labels.shape[0], G.z_dim],
260
- device=device).split(batch_gpu)
261
- grid_c = torch.from_numpy(labels).to(device).split(batch_gpu)
262
- images = torch.cat([G_ema(z=z, c=c, noise_mode='const').cpu()
263
- for z, c in zip(grid_z, grid_c)]).numpy()
264
- save_image_grid(images, os.path.join(
265
- run_dir, 'fakes_init.png'), drange=[-1, 1], grid_size=grid_size)
266
-
267
- # Initialize logs.
268
- if rank == 0:
269
- print('Initializing logs...')
270
- stats_collector = training_stats.Collector(regex='.*')
271
- stats_metrics = dict()
272
- stats_jsonl = None
273
- stats_tfevents = None
274
- if rank == 0:
275
- stats_jsonl = open(os.path.join(run_dir, 'stats.jsonl'), 'wt')
276
- try:
277
- import torch.utils.tensorboard as tensorboard
278
- stats_tfevents = tensorboard.SummaryWriter(run_dir)
279
- except ImportError as err:
280
- print('Skipping tfevents export:', err)
281
-
282
- # Train.
283
- if rank == 0:
284
- print(f'Training for {total_kimg} kimg...')
285
- print()
286
- cur_nimg = resume_kimg * 1000
287
- cur_tick = 0
288
- tick_start_nimg = cur_nimg
289
- tick_start_time = time.time()
290
- maintenance_time = tick_start_time - start_time
291
- batch_idx = 0
292
- if progress_fn is not None:
293
- progress_fn(0, total_kimg)
294
- while True:
295
-
296
- # Fetch training data.
297
- with torch.autograd.profiler.record_function('data_fetch'):
298
- phase_real_img, phase_real_c = next(training_set_iterator)
299
- phase_real_img = (phase_real_img.to(device).to(
300
- torch.float32) / 127.5 - 1).split(batch_gpu)
301
- phase_real_c = phase_real_c.to(device).split(batch_gpu)
302
- all_gen_z = torch.randn(
303
- [len(phases) * batch_size, G.z_dim], device=device)
304
- all_gen_z = [phase_gen_z.split(
305
- batch_gpu) for phase_gen_z in all_gen_z.split(batch_size)]
306
- all_gen_c = [training_set.get_label(np.random.randint(
307
- len(training_set))) for _ in range(len(phases) * batch_size)]
308
- all_gen_c = torch.from_numpy(
309
- np.stack(all_gen_c)).pin_memory().to(device)
310
- all_gen_c = [phase_gen_c.split(
311
- batch_gpu) for phase_gen_c in all_gen_c.split(batch_size)]
312
-
313
- # Execute training phases.
314
- for phase, phase_gen_z, phase_gen_c in zip(phases, all_gen_z, all_gen_c):
315
- if batch_idx % phase.interval != 0:
316
- continue
317
- if phase.start_event is not None:
318
- phase.start_event.record(torch.cuda.current_stream(device))
319
-
320
- # Accumulate gradients.
321
- phase.opt.zero_grad(set_to_none=True)
322
- phase.module.requires_grad_(True)
323
- for real_img, real_c, gen_z, gen_c in zip(phase_real_img, phase_real_c, phase_gen_z, phase_gen_c):
324
- loss.accumulate_gradients(phase=phase.name, real_img=real_img, real_c=real_c,
325
- gen_z=gen_z, gen_c=gen_c, gain=phase.interval, cur_nimg=cur_nimg)
326
- phase.module.requires_grad_(False)
327
-
328
- # Update weights.
329
- with torch.autograd.profiler.record_function(phase.name + '_opt'):
330
- params = [param for param in phase.module.parameters()
331
- if param.grad is not None]
332
- if len(params) > 0:
333
- flat = torch.cat([param.grad.flatten()
334
- for param in params])
335
- if num_gpus > 1:
336
- torch.distributed.all_reduce(flat)
337
- flat /= num_gpus
338
- misc.nan_to_num(flat, nan=0, posinf=1e5,
339
- neginf=-1e5, out=flat)
340
- grads = flat.split([param.numel() for param in params])
341
- for param, grad in zip(params, grads):
342
- param.grad = grad.reshape(param.shape)
343
- phase.opt.step()
344
-
345
- # Phase done.
346
- if phase.end_event is not None:
347
- phase.end_event.record(torch.cuda.current_stream(device))
348
-
349
- # Update G_ema.
350
- with torch.autograd.profiler.record_function('Gema'):
351
- ema_nimg = ema_kimg * 1000
352
- if ema_rampup is not None:
353
- ema_nimg = min(ema_nimg, cur_nimg * ema_rampup)
354
- ema_beta = 0.5 ** (batch_size / max(ema_nimg, 1e-8))
355
- for p_ema, p in zip(G_ema.parameters(), G.parameters()):
356
- p_ema.copy_(p.lerp(p_ema, ema_beta))
357
- for b_ema, b in zip(G_ema.buffers(), G.buffers()):
358
- b_ema.copy_(b)
359
-
360
- # Update state.
361
- cur_nimg += batch_size
362
- batch_idx += 1
363
-
364
- # Execute ADA heuristic.
365
- if (ada_stats is not None) and (batch_idx % ada_interval == 0):
366
- ada_stats.update()
367
- adjust = np.sign(ada_stats['Loss/signs/real'] - ada_target) * \
368
- (batch_size * ada_interval) / (ada_kimg * 1000)
369
- augment_pipe.p.copy_(
370
- (augment_pipe.p + adjust).max(misc.constant(0, device=device)))
371
-
372
- # Perform maintenance tasks once per tick.
373
- done = (cur_nimg >= total_kimg * 1000)
374
- if (not done) and (cur_tick != 0) and (cur_nimg < tick_start_nimg + kimg_per_tick * 1000):
375
- continue
376
-
377
- # Print status line, accumulating the same information in training_stats.
378
- tick_end_time = time.time()
379
- fields = []
380
- fields += [
381
- f"tick {training_stats.report0('Progress/tick', cur_tick):<5d}"]
382
- fields += [
383
- f"kimg {training_stats.report0('Progress/kimg', cur_nimg / 1e3):<8.1f}"]
384
- fields += [
385
- f"time {dnnlib.util.format_time(training_stats.report0('Timing/total_sec', tick_end_time - start_time)):<12s}"]
386
- fields += [
387
- f"sec/tick {training_stats.report0('Timing/sec_per_tick', tick_end_time - tick_start_time):<7.1f}"]
388
- fields += [
389
- f"sec/kimg {training_stats.report0('Timing/sec_per_kimg', (tick_end_time - tick_start_time) / (cur_nimg - tick_start_nimg) * 1e3):<7.2f}"]
390
- fields += [
391
- f"maintenance {training_stats.report0('Timing/maintenance_sec', maintenance_time):<6.1f}"]
392
- fields += [
393
- f"cpumem {training_stats.report0('Resources/cpu_mem_gb', psutil.Process(os.getpid()).memory_info().rss / 2**30):<6.2f}"]
394
- fields += [
395
- f"gpumem {training_stats.report0('Resources/peak_gpu_mem_gb', torch.cuda.max_memory_allocated(device) / 2**30):<6.2f}"]
396
- fields += [
397
- f"reserved {training_stats.report0('Resources/peak_gpu_mem_reserved_gb', torch.cuda.max_memory_reserved(device) / 2**30):<6.2f}"]
398
- torch.cuda.reset_peak_memory_stats()
399
- fields += [
400
- f"augment {training_stats.report0('Progress/augment', float(augment_pipe.p.cpu()) if augment_pipe is not None else 0):.3f}"]
401
- training_stats.report0('Timing/total_hours',
402
- (tick_end_time - start_time) / (60 * 60))
403
- training_stats.report0('Timing/total_days',
404
- (tick_end_time - start_time) / (24 * 60 * 60))
405
- if rank == 0:
406
- print(' '.join(fields))
407
-
408
- # Check for abort.
409
- if (not done) and (abort_fn is not None) and abort_fn():
410
- done = True
411
- if rank == 0:
412
- print()
413
- print('Aborting...')
414
-
415
- # Save image snapshot.
416
- if (rank == 0) and (image_snapshot_ticks is not None) and (done or cur_tick % image_snapshot_ticks == 0):
417
- images = torch.cat([G_ema(z=z, c=c, noise_mode='const').cpu()
418
- for z, c in zip(grid_z, grid_c)]).numpy()
419
- save_image_grid(images, os.path.join(
420
- run_dir, f'fakes{cur_nimg//1000:06d}.png'), drange=[-1, 1], grid_size=grid_size)
421
-
422
- # Save network snapshot.
423
- snapshot_pkl = None
424
- snapshot_data = None
425
- if (network_snapshot_ticks is not None) and (done or cur_tick % network_snapshot_ticks == 0):
426
- snapshot_data = dict(G=G, D=D, G_ema=G_ema, augment_pipe=augment_pipe,
427
- training_set_kwargs=dict(training_set_kwargs))
428
- for key, value in snapshot_data.items():
429
- if isinstance(value, torch.nn.Module):
430
- value = copy.deepcopy(value).eval().requires_grad_(False)
431
- if num_gpus > 1:
432
- misc.check_ddp_consistency(
433
- value, ignore_regex=r'.*\.[^.]+_(avg|ema)')
434
- for param in misc.params_and_buffers(value):
435
- torch.distributed.broadcast(param, src=0)
436
- snapshot_data[key] = value.cpu()
437
- del value # conserve memory
438
- snapshot_pkl = os.path.join(
439
- run_dir, f'network-snapshot-{cur_nimg//1000:06d}.pkl')
440
- if rank == 0:
441
- with open(snapshot_pkl, 'wb') as f:
442
- pickle.dump(snapshot_data, f)
443
-
444
- # Evaluate metrics.
445
- if (snapshot_data is not None) and (len(metrics) > 0):
446
- if rank == 0:
447
- print('Evaluating metrics...')
448
- for metric in metrics:
449
- result_dict = metric_main.calc_metric(metric=metric, G=snapshot_data['G_ema'],
450
- dataset_kwargs=training_set_kwargs, num_gpus=num_gpus, rank=rank, device=device)
451
- if rank == 0:
452
- metric_main.report_metric(
453
- result_dict, run_dir=run_dir, snapshot_pkl=snapshot_pkl)
454
- stats_metrics.update(result_dict.results)
455
- del snapshot_data # conserve memory
456
-
457
- # Collect statistics.
458
- for phase in phases:
459
- value = []
460
- if (phase.start_event is not None) and (phase.end_event is not None):
461
- phase.end_event.synchronize()
462
- value = phase.start_event.elapsed_time(phase.end_event)
463
- training_stats.report0('Timing/' + phase.name, value)
464
- stats_collector.update()
465
- stats_dict = stats_collector.as_dict()
466
-
467
- # Update logs.
468
- timestamp = time.time()
469
- if stats_jsonl is not None:
470
- fields = dict(stats_dict, timestamp=timestamp)
471
- stats_jsonl.write(json.dumps(fields) + '\n')
472
- stats_jsonl.flush()
473
- if stats_tfevents is not None:
474
- global_step = int(cur_nimg / 1e3)
475
- walltime = timestamp - start_time
476
- for name, value in stats_dict.items():
477
- stats_tfevents.add_scalar(
478
- name, value.mean, global_step=global_step, walltime=walltime)
479
- for name, value in stats_metrics.items():
480
- stats_tfevents.add_scalar(
481
- f'Metrics/{name}', value, global_step=global_step, walltime=walltime)
482
- stats_tfevents.flush()
483
- if progress_fn is not None:
484
- progress_fn(cur_nimg // 1000, total_kimg)
485
-
486
- # Update state.
487
- cur_tick += 1
488
- tick_start_nimg = cur_nimg
489
- tick_start_time = time.time()
490
- maintenance_time = tick_start_time - tick_end_time
491
- if done:
492
- break
493
-
494
- # Done.
495
- if rank == 0:
496
- print()
497
- print('Exiting...')
498
-
499
- # ----------------------------------------------------------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AnTo2209/3D_Zeroshot_Neural_Style_Transfer/inference.py DELETED
@@ -1,78 +0,0 @@
1
- import os
2
- from pathlib import Path
3
-
4
- import torch
5
- from lightning_fabric import seed_everything
6
- from PIL import Image, ImageFile
7
-
8
- from src.dataset import DATASET_REGISTRY
9
- from src.decoder import DECODER_REGISTRY
10
- from src.utils.opt import Opts
11
- import torchvision.transforms as T
12
-
13
- from src.utils.renderer import evaluation_feature, evaluation_feature_path, OctreeRender_trilinear_fast
14
-
15
-
16
- def inference(cfg, render_mode: str, image=None):
17
- device = "cuda" if torch.cuda.is_available() else "cpu"
18
-
19
- ckpt = torch.load(cfg["model"]["tensorf"]["ckpt"], map_location=device)
20
- kwargs = ckpt['kwargs']
21
- kwargs.update({'device': device})
22
- print(device)
23
- tensorf = DECODER_REGISTRY.get(cfg["model"]["tensorf"]["model_name"])(**kwargs)
24
- tensorf.change_to_feature_mod(cfg["model"]["tensorf"]["lamb_sh"], device)
25
- tensorf.change_to_style_mod(device)
26
- tensorf.load(ckpt)
27
- tensorf.eval()
28
- tensorf.rayMarch_weight_thres = cfg["model"]["tensorf"]["rm_weight_mask_thre"]
29
-
30
- logfolder = os.path.dirname("./checkpoints")
31
- renderer= OctreeRender_trilinear_fast
32
-
33
- trans = T.Compose([T.Resize(size=(256, 256)), T.ToTensor()])
34
- if image:
35
- if torch.cuda.is_available():
36
- style_img = trans(image).cuda()[None, ...]
37
- else:
38
- style_img = trans(image)[None, ...]
39
- else:
40
- style_img = trans(Image.open(cfg["global"]["style_img"])).cuda()[None, ...]
41
- style_name = Path(cfg["global"]["style_img"]).stem
42
-
43
- if render_mode == "render_train":
44
- dataset = DATASET_REGISTRY.get(cfg["dataset"]["name"])(
45
- **cfg["dataset"]["train"]["params"],
46
- )
47
- os.makedirs(f'{logfolder}/{cfg["global"]["expname"]}/imgs_train_all/{style_name}', exist_ok=True)
48
- result = evaluation_feature(dataset, tensorf, renderer, cfg["sampler"]["params"]["chunk_size"],
49
- f'{logfolder}/{cfg["global"]["expname"]}/imgs_train_all/{style_name}',
50
- N_vis=-1, N_samples=-1, white_bg=dataset.white_bg, ndc_ray=cfg["model"]["tensorf"]["ndc_ray"],
51
- style_img=style_img, device=device)
52
-
53
- if render_mode == "render_test":
54
- dataset = DATASET_REGISTRY.get(cfg["dataset"]["name"])(
55
- **cfg["dataset"]["val"]["params"],
56
- )
57
- os.makedirs(f'{logfolder}/{cfg["global"]["expname"]}/imgs_train_all/{style_name}', exist_ok=True)
58
- result = evaluation_feature(dataset, tensorf, renderer, cfg["sampler"]["params"]["chunk_size"],
59
- f'{logfolder}/{cfg["global"]["expname"]}/imgs_train_all/{style_name}',
60
- N_vis=-1, N_samples=-1, white_bg=dataset.white_bg, ndc_ray=cfg["model"]["tensorf"]["ndc_ray"],
61
- style_img=style_img, device=device)
62
-
63
- if render_mode == "render_path":
64
- dataset = DATASET_REGISTRY.get(cfg["dataset"]["name"])(
65
- **cfg["dataset"]["val"]["params"],
66
- )
67
- c2ws = dataset.render_path
68
- os.makedirs(f'{logfolder}/{cfg["global"]["expname"]}/imgs_path_all/{style_name}', exist_ok=True)
69
- result = evaluation_feature_path(dataset, tensorf, c2ws, renderer, cfg["sampler"]["params"]["chunk_size"],
70
- f'{logfolder}/{cfg["global"]["expname"]}/imgs_path_all/{style_name}',
71
- N_vis=-1, N_samples=-1, white_bg=dataset.white_bg, ndc_ray=cfg["model"]["tensorf"]["ndc_ray"],
72
- style_img=style_img, device=device)
73
- return result
74
-
75
- if __name__ == "__main__":
76
- cfg = Opts(cfg="configs/style_inference.yml").parse_args()
77
- seed_everything(seed=cfg["global"]["SEED"])
78
- inference(cfg, "render_test")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/en/api/schedulers/unipc.md DELETED
@@ -1,24 +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
- # UniPC
14
-
15
- ## Overview
16
-
17
- UniPC is a training-free framework designed for the fast sampling of diffusion models, which consists of a corrector (UniC) and a predictor (UniP) that share a unified analytical form and support arbitrary orders.
18
-
19
- For more details about the method, please refer to the [paper](https://arxiv.org/abs/2302.04867) and the [code](https://github.com/wl-zhao/UniPC).
20
-
21
- Fast Sampling of Diffusion Models with Exponential Integrator.
22
-
23
- ## UniPCMultistepScheduler
24
- [[autodoc]] UniPCMultistepScheduler
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/src/diffusers/pipelines/controlnet/__init__.py DELETED
@@ -1,23 +0,0 @@
1
- from ...utils import (
2
- OptionalDependencyNotAvailable,
3
- is_flax_available,
4
- is_torch_available,
5
- is_transformers_available,
6
- )
7
-
8
-
9
- try:
10
- if not (is_transformers_available() and is_torch_available()):
11
- raise OptionalDependencyNotAvailable()
12
- except OptionalDependencyNotAvailable:
13
- from ...utils.dummy_torch_and_transformers_objects import * # noqa F403
14
- else:
15
- from .multicontrolnet import MultiControlNetModel
16
- from .pipeline_controlnet import StableDiffusionControlNetPipeline
17
- from .pipeline_controlnet_img2img import StableDiffusionControlNetImg2ImgPipeline
18
- from .pipeline_controlnet_inpaint import StableDiffusionControlNetInpaintPipeline
19
- from .pipeline_controlnet_sd_xl import StableDiffusionXLControlNetPipeline
20
-
21
-
22
- if is_transformers_available() and is_flax_available():
23
- from .pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Anindya/Marketing_Campaign_LLM/app.py DELETED
@@ -1,120 +0,0 @@
1
- import os
2
- import streamlit as st
3
- from dotenv import load_dotenv
4
- from langchain.llms import OpenAI
5
- from langchain.prompts import PromptTemplate, FewShotPromptTemplate
6
- from langchain.prompts.example_selector import LengthBasedExampleSelector
7
-
8
- load_dotenv()
9
-
10
-
11
- def get_llm_response(query, action, age, word_limit):
12
- """Get LLM Response"""
13
- llm = OpenAI(temperature=0.9, model="text-davinci-003")
14
-
15
- examples = [
16
- {
17
- "query": "What is a mobile?",
18
- "answer": "A mobile is a magical device that fits in your pocket, like a mini-enchanted playground. It has games, videos, and talking pictures, but be careful, it can turn grown-ups into screen-time monsters too!",
19
- },
20
- {
21
- "query": "What are your dreams?",
22
- "answer": "My dreams are like colorful adventures, where I become a superhero and save the day! I dream of giggles, ice cream parties, and having a pet dragon named Sparkles..",
23
- },
24
- {
25
- "query": " What are your ambitions?",
26
- "answer": "I want to be a super funny comedian, spreading laughter everywhere I go! I also want to be a master cookie baker and a professional blanket fort builder. Being mischievous and sweet is just my bonus superpower!",
27
- },
28
- {
29
- "query": "What happens when you get sick?",
30
- "answer": "When I get sick, it's like a sneaky monster visits. I feel tired, sniffly, and need lots of cuddles. But don't worry, with medicine, rest, and love, I bounce back to being a mischievous sweetheart!",
31
- },
32
- {
33
- "query": "WHow much do you love your dad?",
34
- "answer": "Oh, I love my dad to the moon and back, with sprinkles and unicorns on top! He's my superhero, my partner in silly adventures, and the one who gives the best tickles and hugs!",
35
- },
36
- {
37
- "query": "Tell me about your friend?",
38
- "answer": "My friend is like a sunshine rainbow! We laugh, play, and have magical parties together. They always listen, share their toys, and make me feel special. Friendship is the best adventure!",
39
- },
40
- {
41
- "query": "What math means to you?",
42
- "answer": "Math is like a puzzle game, full of numbers and shapes. It helps me count my toys, build towers, and share treats equally. It's fun and makes my brain sparkle!",
43
- },
44
- {
45
- "query": "What is your fear?",
46
- "answer": "Sometimes I'm scared of thunderstorms and monsters under my bed. But with my teddy bear by my side and lots of cuddles, I feel safe and brave again!",
47
- },
48
- ]
49
-
50
- example_template = """Question: {query}
51
- Answer: {answer}"""
52
-
53
- example_prompt = PromptTemplate(
54
- template=example_template, input_variables=["query", "answer"]
55
- )
56
-
57
- example_selector = LengthBasedExampleSelector(
58
- examples=examples, example_prompt=example_prompt, max_length=word_limit
59
- )
60
-
61
- prefix = """You are a {template_age} and {template_task}.
62
- Here are some examples:"""
63
-
64
- suffix = """
65
- Question: {template_query}
66
- Answer: """
67
-
68
- prompt = FewShotPromptTemplate(
69
- example_selector=example_selector,
70
- example_prompt=example_prompt,
71
- example_separator="/n/n",
72
- prefix=prefix,
73
- suffix=suffix,
74
- input_variables=["template_age", "template_task", "template_query"],
75
- )
76
-
77
- llm_response = llm(
78
- prompt.format(template_age=age, template_task=action, template_query=query)
79
- )
80
- return llm_response
81
-
82
-
83
- st.set_page_config(page_title="Marketing Tool", page_icon=":books:")
84
- st.header("Marketing Tool :books:")
85
-
86
- if "OPENAI_API_KEY" not in os.environ:
87
- openai_api_key = st.text_input(
88
- label="OpenAI API Key: ",
89
- type="password",
90
- placeholder="Paste the OpenI API Key here to use gpt models",
91
- )
92
- submit = st.button("Submit")
93
- if submit and openai_api_key != "":
94
- os.environ["OPENAI_API_KEY"] = openai_api_key
95
-
96
- if "OPENAI_API_KEY" in os.environ:
97
- user_query = st.text_area(label="Enter Text Here...", height=150)
98
- user_action = st.selectbox(
99
- label="Select Task: ",
100
- options=("Generate Tweet", "Generate Post"),
101
- key="select_action",
102
- )
103
- # user_age = st.selectbox(
104
- # label="Select Age Group: ",
105
- # options=("Kid", "Adult", "Senior Cityzen"),
106
- # key="select_age",
107
- # )
108
- user_word_limit = st.slider(
109
- label="Word limit: ", min_value=1, max_value=250, value=25
110
- )
111
- generate = st.button("Generate")
112
- if generate:
113
- st.write(
114
- get_llm_response(
115
- query=user_query,
116
- action=user_action,
117
- age="Kid",
118
- word_limit=user_word_limit,
119
- )
120
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Antoine245/bot/README.md DELETED
@@ -1,33 +0,0 @@
1
- ---
2
- title: Bot
3
- emoji: 🦀
4
- colorFrom: indigo
5
- colorTo: pink
6
- sdk: gradio
7
- app_file: app.py
8
- pinned: false
9
- license: openrail
10
- ---
11
-
12
- # Easy Chatbot with PaLM API
13
-
14
- 1. go to https://makersuite.google.com/app/home
15
- 2. create your bot in the chat prompt
16
- 3. change app.py file with your own context and examples
17
- 4. add your own palm api key https://makersuite.google.com/app/apikey to your HF environment (cf https://huggingface.co/docs/huggingface_hub/guides/manage-spaces)
18
- 5. ready to use chatbot that can be used as embedded in any websites (cf https://comparateur-image.web.app/bot/)
19
-
20
-
21
- ### Errors
22
-
23
- 1. clear button (gr.ClearButton needs a fix in embedded websites), I use a basic button until fixed
24
-
25
- ### Use community if any question/request
26
-
27
- ### Please check mkersuite quickstart
28
-
29
- Makersuite allows you to change context and examples in order to get the best chatbot and then export the code. You can then try it in gradio by cloning this space and changing context and examples.
30
-
31
- Check out https://developers.generativeai.google/tutorials/makersuite_quickstart
32
-
33
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_internal/models/search_scope.py DELETED
@@ -1,132 +0,0 @@
1
- import itertools
2
- import logging
3
- import os
4
- import posixpath
5
- import urllib.parse
6
- from typing import List
7
-
8
- from pip._vendor.packaging.utils import canonicalize_name
9
-
10
- from pip._internal.models.index import PyPI
11
- from pip._internal.utils.compat import has_tls
12
- from pip._internal.utils.misc import normalize_path, redact_auth_from_url
13
-
14
- logger = logging.getLogger(__name__)
15
-
16
-
17
- class SearchScope:
18
-
19
- """
20
- Encapsulates the locations that pip is configured to search.
21
- """
22
-
23
- __slots__ = ["find_links", "index_urls", "no_index"]
24
-
25
- @classmethod
26
- def create(
27
- cls,
28
- find_links: List[str],
29
- index_urls: List[str],
30
- no_index: bool,
31
- ) -> "SearchScope":
32
- """
33
- Create a SearchScope object after normalizing the `find_links`.
34
- """
35
- # Build find_links. If an argument starts with ~, it may be
36
- # a local file relative to a home directory. So try normalizing
37
- # it and if it exists, use the normalized version.
38
- # This is deliberately conservative - it might be fine just to
39
- # blindly normalize anything starting with a ~...
40
- built_find_links: List[str] = []
41
- for link in find_links:
42
- if link.startswith("~"):
43
- new_link = normalize_path(link)
44
- if os.path.exists(new_link):
45
- link = new_link
46
- built_find_links.append(link)
47
-
48
- # If we don't have TLS enabled, then WARN if anyplace we're looking
49
- # relies on TLS.
50
- if not has_tls():
51
- for link in itertools.chain(index_urls, built_find_links):
52
- parsed = urllib.parse.urlparse(link)
53
- if parsed.scheme == "https":
54
- logger.warning(
55
- "pip is configured with locations that require "
56
- "TLS/SSL, however the ssl module in Python is not "
57
- "available."
58
- )
59
- break
60
-
61
- return cls(
62
- find_links=built_find_links,
63
- index_urls=index_urls,
64
- no_index=no_index,
65
- )
66
-
67
- def __init__(
68
- self,
69
- find_links: List[str],
70
- index_urls: List[str],
71
- no_index: bool,
72
- ) -> None:
73
- self.find_links = find_links
74
- self.index_urls = index_urls
75
- self.no_index = no_index
76
-
77
- def get_formatted_locations(self) -> str:
78
- lines = []
79
- redacted_index_urls = []
80
- if self.index_urls and self.index_urls != [PyPI.simple_url]:
81
- for url in self.index_urls:
82
- redacted_index_url = redact_auth_from_url(url)
83
-
84
- # Parse the URL
85
- purl = urllib.parse.urlsplit(redacted_index_url)
86
-
87
- # URL is generally invalid if scheme and netloc is missing
88
- # there are issues with Python and URL parsing, so this test
89
- # is a bit crude. See bpo-20271, bpo-23505. Python doesn't
90
- # always parse invalid URLs correctly - it should raise
91
- # exceptions for malformed URLs
92
- if not purl.scheme and not purl.netloc:
93
- logger.warning(
94
- 'The index url "%s" seems invalid, please provide a scheme.',
95
- redacted_index_url,
96
- )
97
-
98
- redacted_index_urls.append(redacted_index_url)
99
-
100
- lines.append(
101
- "Looking in indexes: {}".format(", ".join(redacted_index_urls))
102
- )
103
-
104
- if self.find_links:
105
- lines.append(
106
- "Looking in links: {}".format(
107
- ", ".join(redact_auth_from_url(url) for url in self.find_links)
108
- )
109
- )
110
- return "\n".join(lines)
111
-
112
- def get_index_urls_locations(self, project_name: str) -> List[str]:
113
- """Returns the locations found via self.index_urls
114
-
115
- Checks the url_name on the main (first in the list) index and
116
- use this url_name to produce all locations
117
- """
118
-
119
- def mkurl_pypi_url(url: str) -> str:
120
- loc = posixpath.join(
121
- url, urllib.parse.quote(canonicalize_name(project_name))
122
- )
123
- # For maximum compatibility with easy_install, ensure the path
124
- # ends in a trailing slash. Although this isn't in the spec
125
- # (and PyPI can handle it without the slash) some other index
126
- # implementations might break if they relied on easy_install's
127
- # behavior.
128
- if not loc.endswith("/"):
129
- loc = loc + "/"
130
- return loc
131
-
132
- return [mkurl_pypi_url(url) for url in self.index_urls]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/command/editable_wheel.py DELETED
@@ -1,844 +0,0 @@
1
- """
2
- Create a wheel that, when installed, will make the source package 'editable'
3
- (add it to the interpreter's path, including metadata) per PEP 660. Replaces
4
- 'setup.py develop'.
5
-
6
- .. note::
7
- One of the mechanisms briefly mentioned in PEP 660 to implement editable installs is
8
- to create a separated directory inside ``build`` and use a .pth file to point to that
9
- directory. In the context of this file such directory is referred as
10
- *auxiliary build directory* or ``auxiliary_dir``.
11
- """
12
-
13
- import logging
14
- import os
15
- import re
16
- import shutil
17
- import sys
18
- import traceback
19
- import warnings
20
- from contextlib import suppress
21
- from enum import Enum
22
- from inspect import cleandoc
23
- from itertools import chain
24
- from pathlib import Path
25
- from tempfile import TemporaryDirectory
26
- from typing import (
27
- TYPE_CHECKING,
28
- Dict,
29
- Iterable,
30
- Iterator,
31
- List,
32
- Mapping,
33
- Optional,
34
- Tuple,
35
- TypeVar,
36
- Union,
37
- )
38
-
39
- from setuptools import Command, SetuptoolsDeprecationWarning, errors, namespaces
40
- from setuptools.command.build_py import build_py as build_py_cls
41
- from setuptools.discovery import find_package_path
42
- from setuptools.dist import Distribution
43
-
44
- if TYPE_CHECKING:
45
- from wheel.wheelfile import WheelFile # noqa
46
-
47
- if sys.version_info >= (3, 8):
48
- from typing import Protocol
49
- elif TYPE_CHECKING:
50
- from typing_extensions import Protocol
51
- else:
52
- from abc import ABC as Protocol
53
-
54
- _Path = Union[str, Path]
55
- _P = TypeVar("_P", bound=_Path)
56
- _logger = logging.getLogger(__name__)
57
-
58
-
59
- class _EditableMode(Enum):
60
- """
61
- Possible editable installation modes:
62
- `lenient` (new files automatically added to the package - DEFAULT);
63
- `strict` (requires a new installation when files are added/removed); or
64
- `compat` (attempts to emulate `python setup.py develop` - DEPRECATED).
65
- """
66
-
67
- STRICT = "strict"
68
- LENIENT = "lenient"
69
- COMPAT = "compat" # TODO: Remove `compat` after Dec/2022.
70
-
71
- @classmethod
72
- def convert(cls, mode: Optional[str]) -> "_EditableMode":
73
- if not mode:
74
- return _EditableMode.LENIENT # default
75
-
76
- _mode = mode.upper()
77
- if _mode not in _EditableMode.__members__:
78
- raise errors.OptionError(f"Invalid editable mode: {mode!r}. Try: 'strict'.")
79
-
80
- if _mode == "COMPAT":
81
- msg = """
82
- The 'compat' editable mode is transitional and will be removed
83
- in future versions of `setuptools`.
84
- Please adapt your code accordingly to use either the 'strict' or the
85
- 'lenient' modes.
86
-
87
- For more information, please check:
88
- https://setuptools.pypa.io/en/latest/userguide/development_mode.html
89
- """
90
- warnings.warn(msg, SetuptoolsDeprecationWarning)
91
-
92
- return _EditableMode[_mode]
93
-
94
-
95
- _STRICT_WARNING = """
96
- New or renamed files may not be automatically picked up without a new installation.
97
- """
98
-
99
- _LENIENT_WARNING = """
100
- Options like `package-data`, `include/exclude-package-data` or
101
- `packages.find.exclude/include` may have no effect.
102
- """
103
-
104
-
105
- class editable_wheel(Command):
106
- """Build 'editable' wheel for development.
107
- (This command is reserved for internal use of setuptools).
108
- """
109
-
110
- description = "create a PEP 660 'editable' wheel"
111
-
112
- user_options = [
113
- ("dist-dir=", "d", "directory to put final built distributions in"),
114
- ("dist-info-dir=", "I", "path to a pre-build .dist-info directory"),
115
- ("mode=", None, cleandoc(_EditableMode.__doc__ or "")),
116
- ]
117
-
118
- def initialize_options(self):
119
- self.dist_dir = None
120
- self.dist_info_dir = None
121
- self.project_dir = None
122
- self.mode = None
123
-
124
- def finalize_options(self):
125
- dist = self.distribution
126
- self.project_dir = dist.src_root or os.curdir
127
- self.package_dir = dist.package_dir or {}
128
- self.dist_dir = Path(self.dist_dir or os.path.join(self.project_dir, "dist"))
129
-
130
- def run(self):
131
- try:
132
- self.dist_dir.mkdir(exist_ok=True)
133
- self._ensure_dist_info()
134
-
135
- # Add missing dist_info files
136
- self.reinitialize_command("bdist_wheel")
137
- bdist_wheel = self.get_finalized_command("bdist_wheel")
138
- bdist_wheel.write_wheelfile(self.dist_info_dir)
139
-
140
- self._create_wheel_file(bdist_wheel)
141
- except Exception as ex:
142
- traceback.print_exc()
143
- msg = """
144
- Support for editable installs via PEP 660 was recently introduced
145
- in `setuptools`. If you are seeing this error, please report to:
146
-
147
- https://github.com/pypa/setuptools/issues
148
-
149
- Meanwhile you can try the legacy behavior by setting an
150
- environment variable and trying to install again:
151
-
152
- SETUPTOOLS_ENABLE_FEATURES="legacy-editable"
153
- """
154
- raise errors.InternalError(cleandoc(msg)) from ex
155
-
156
- def _ensure_dist_info(self):
157
- if self.dist_info_dir is None:
158
- dist_info = self.reinitialize_command("dist_info")
159
- dist_info.output_dir = self.dist_dir
160
- dist_info.ensure_finalized()
161
- dist_info.run()
162
- self.dist_info_dir = dist_info.dist_info_dir
163
- else:
164
- assert str(self.dist_info_dir).endswith(".dist-info")
165
- assert Path(self.dist_info_dir, "METADATA").exists()
166
-
167
- def _install_namespaces(self, installation_dir, pth_prefix):
168
- # XXX: Only required to support the deprecated namespace practice
169
- dist = self.distribution
170
- if not dist.namespace_packages:
171
- return
172
-
173
- src_root = Path(self.project_dir, self.package_dir.get("", ".")).resolve()
174
- installer = _NamespaceInstaller(dist, installation_dir, pth_prefix, src_root)
175
- installer.install_namespaces()
176
-
177
- def _find_egg_info_dir(self) -> Optional[str]:
178
- parent_dir = Path(self.dist_info_dir).parent if self.dist_info_dir else Path()
179
- candidates = map(str, parent_dir.glob("*.egg-info"))
180
- return next(candidates, None)
181
-
182
- def _configure_build(
183
- self, name: str, unpacked_wheel: _Path, build_lib: _Path, tmp_dir: _Path
184
- ):
185
- """Configure commands to behave in the following ways:
186
-
187
- - Build commands can write to ``build_lib`` if they really want to...
188
- (but this folder is expected to be ignored and modules are expected to live
189
- in the project directory...)
190
- - Binary extensions should be built in-place (editable_mode = True)
191
- - Data/header/script files are not part of the "editable" specification
192
- so they are written directly to the unpacked_wheel directory.
193
- """
194
- # Non-editable files (data, headers, scripts) are written directly to the
195
- # unpacked_wheel
196
-
197
- dist = self.distribution
198
- wheel = str(unpacked_wheel)
199
- build_lib = str(build_lib)
200
- data = str(Path(unpacked_wheel, f"{name}.data", "data"))
201
- headers = str(Path(unpacked_wheel, f"{name}.data", "headers"))
202
- scripts = str(Path(unpacked_wheel, f"{name}.data", "scripts"))
203
-
204
- # egg-info may be generated again to create a manifest (used for package data)
205
- egg_info = dist.reinitialize_command("egg_info", reinit_subcommands=True)
206
- egg_info.egg_base = str(tmp_dir)
207
- egg_info.ignore_egg_info_in_manifest = True
208
-
209
- build = dist.reinitialize_command("build", reinit_subcommands=True)
210
- install = dist.reinitialize_command("install", reinit_subcommands=True)
211
-
212
- build.build_platlib = build.build_purelib = build.build_lib = build_lib
213
- install.install_purelib = install.install_platlib = install.install_lib = wheel
214
- install.install_scripts = build.build_scripts = scripts
215
- install.install_headers = headers
216
- install.install_data = data
217
-
218
- install_scripts = dist.get_command_obj("install_scripts")
219
- install_scripts.no_ep = True
220
-
221
- build.build_temp = str(tmp_dir)
222
-
223
- build_py = dist.get_command_obj("build_py")
224
- build_py.compile = False
225
- build_py.existing_egg_info_dir = self._find_egg_info_dir()
226
-
227
- self._set_editable_mode()
228
-
229
- build.ensure_finalized()
230
- install.ensure_finalized()
231
-
232
- def _set_editable_mode(self):
233
- """Set the ``editable_mode`` flag in the build sub-commands"""
234
- dist = self.distribution
235
- build = dist.get_command_obj("build")
236
- for cmd_name in build.get_sub_commands():
237
- cmd = dist.get_command_obj(cmd_name)
238
- if hasattr(cmd, "editable_mode"):
239
- cmd.editable_mode = True
240
- elif hasattr(cmd, "inplace"):
241
- cmd.inplace = True # backward compatibility with distutils
242
-
243
- def _collect_build_outputs(self) -> Tuple[List[str], Dict[str, str]]:
244
- files: List[str] = []
245
- mapping: Dict[str, str] = {}
246
- build = self.get_finalized_command("build")
247
-
248
- for cmd_name in build.get_sub_commands():
249
- cmd = self.get_finalized_command(cmd_name)
250
- if hasattr(cmd, "get_outputs"):
251
- files.extend(cmd.get_outputs() or [])
252
- if hasattr(cmd, "get_output_mapping"):
253
- mapping.update(cmd.get_output_mapping() or {})
254
-
255
- return files, mapping
256
-
257
- def _run_build_commands(
258
- self, dist_name: str, unpacked_wheel: _Path, build_lib: _Path, tmp_dir: _Path
259
- ) -> Tuple[List[str], Dict[str, str]]:
260
- self._configure_build(dist_name, unpacked_wheel, build_lib, tmp_dir)
261
- self._run_build_subcommands()
262
- files, mapping = self._collect_build_outputs()
263
- self._run_install("headers")
264
- self._run_install("scripts")
265
- self._run_install("data")
266
- return files, mapping
267
-
268
- def _run_build_subcommands(self):
269
- """
270
- Issue #3501 indicates that some plugins/customizations might rely on:
271
-
272
- 1. ``build_py`` not running
273
- 2. ``build_py`` always copying files to ``build_lib``
274
-
275
- However both these assumptions may be false in editable_wheel.
276
- This method implements a temporary workaround to support the ecosystem
277
- while the implementations catch up.
278
- """
279
- # TODO: Once plugins/customisations had the chance to catch up, replace
280
- # `self._run_build_subcommands()` with `self.run_command("build")`.
281
- # Also remove _safely_run, TestCustomBuildPy. Suggested date: Aug/2023.
282
- build: Command = self.get_finalized_command("build")
283
- for name in build.get_sub_commands():
284
- cmd = self.get_finalized_command(name)
285
- if name == "build_py" and type(cmd) != build_py_cls:
286
- self._safely_run(name)
287
- else:
288
- self.run_command(name)
289
-
290
- def _safely_run(self, cmd_name: str):
291
- try:
292
- return self.run_command(cmd_name)
293
- except Exception:
294
- msg = f"""{traceback.format_exc()}\n
295
- If you are seeing this warning it is very likely that a setuptools
296
- plugin or customization overrides the `{cmd_name}` command, without
297
- taking into consideration how editable installs run build steps
298
- starting from v64.0.0.
299
-
300
- Plugin authors and developers relying on custom build steps are encouraged
301
- to update their `{cmd_name}` implementation considering the information in
302
- https://setuptools.pypa.io/en/latest/userguide/extension.html
303
- about editable installs.
304
-
305
- For the time being `setuptools` will silence this error and ignore
306
- the faulty command, but this behaviour will change in future versions.\n
307
- """
308
- warnings.warn(msg, SetuptoolsDeprecationWarning, stacklevel=2)
309
-
310
- def _create_wheel_file(self, bdist_wheel):
311
- from wheel.wheelfile import WheelFile
312
-
313
- dist_info = self.get_finalized_command("dist_info")
314
- dist_name = dist_info.name
315
- tag = "-".join(bdist_wheel.get_tag())
316
- build_tag = "0.editable" # According to PEP 427 needs to start with digit
317
- archive_name = f"{dist_name}-{build_tag}-{tag}.whl"
318
- wheel_path = Path(self.dist_dir, archive_name)
319
- if wheel_path.exists():
320
- wheel_path.unlink()
321
-
322
- unpacked_wheel = TemporaryDirectory(suffix=archive_name)
323
- build_lib = TemporaryDirectory(suffix=".build-lib")
324
- build_tmp = TemporaryDirectory(suffix=".build-temp")
325
-
326
- with unpacked_wheel as unpacked, build_lib as lib, build_tmp as tmp:
327
- unpacked_dist_info = Path(unpacked, Path(self.dist_info_dir).name)
328
- shutil.copytree(self.dist_info_dir, unpacked_dist_info)
329
- self._install_namespaces(unpacked, dist_info.name)
330
- files, mapping = self._run_build_commands(dist_name, unpacked, lib, tmp)
331
- strategy = self._select_strategy(dist_name, tag, lib)
332
- with strategy, WheelFile(wheel_path, "w") as wheel_obj:
333
- strategy(wheel_obj, files, mapping)
334
- wheel_obj.write_files(unpacked)
335
-
336
- return wheel_path
337
-
338
- def _run_install(self, category: str):
339
- has_category = getattr(self.distribution, f"has_{category}", None)
340
- if has_category and has_category():
341
- _logger.info(f"Installing {category} as non editable")
342
- self.run_command(f"install_{category}")
343
-
344
- def _select_strategy(
345
- self,
346
- name: str,
347
- tag: str,
348
- build_lib: _Path,
349
- ) -> "EditableStrategy":
350
- """Decides which strategy to use to implement an editable installation."""
351
- build_name = f"__editable__.{name}-{tag}"
352
- project_dir = Path(self.project_dir)
353
- mode = _EditableMode.convert(self.mode)
354
-
355
- if mode is _EditableMode.STRICT:
356
- auxiliary_dir = _empty_dir(Path(self.project_dir, "build", build_name))
357
- return _LinkTree(self.distribution, name, auxiliary_dir, build_lib)
358
-
359
- packages = _find_packages(self.distribution)
360
- has_simple_layout = _simple_layout(packages, self.package_dir, project_dir)
361
- is_compat_mode = mode is _EditableMode.COMPAT
362
- if set(self.package_dir) == {""} and has_simple_layout or is_compat_mode:
363
- # src-layout(ish) is relatively safe for a simple pth file
364
- src_dir = self.package_dir.get("", ".")
365
- return _StaticPth(self.distribution, name, [Path(project_dir, src_dir)])
366
-
367
- # Use a MetaPathFinder to avoid adding accidental top-level packages/modules
368
- return _TopLevelFinder(self.distribution, name)
369
-
370
-
371
- class EditableStrategy(Protocol):
372
- def __call__(self, wheel: "WheelFile", files: List[str], mapping: Dict[str, str]):
373
- ...
374
-
375
- def __enter__(self):
376
- ...
377
-
378
- def __exit__(self, _exc_type, _exc_value, _traceback):
379
- ...
380
-
381
-
382
- class _StaticPth:
383
- def __init__(self, dist: Distribution, name: str, path_entries: List[Path]):
384
- self.dist = dist
385
- self.name = name
386
- self.path_entries = path_entries
387
-
388
- def __call__(self, wheel: "WheelFile", files: List[str], mapping: Dict[str, str]):
389
- entries = "\n".join((str(p.resolve()) for p in self.path_entries))
390
- contents = bytes(f"{entries}\n", "utf-8")
391
- wheel.writestr(f"__editable__.{self.name}.pth", contents)
392
-
393
- def __enter__(self):
394
- msg = f"""
395
- Editable install will be performed using .pth file to extend `sys.path` with:
396
- {list(map(os.fspath, self.path_entries))!r}
397
- """
398
- _logger.warning(msg + _LENIENT_WARNING)
399
- return self
400
-
401
- def __exit__(self, _exc_type, _exc_value, _traceback):
402
- ...
403
-
404
-
405
- class _LinkTree(_StaticPth):
406
- """
407
- Creates a ``.pth`` file that points to a link tree in the ``auxiliary_dir``.
408
-
409
- This strategy will only link files (not dirs), so it can be implemented in
410
- any OS, even if that means using hardlinks instead of symlinks.
411
-
412
- By collocating ``auxiliary_dir`` and the original source code, limitations
413
- with hardlinks should be avoided.
414
- """
415
- def __init__(
416
- self, dist: Distribution,
417
- name: str,
418
- auxiliary_dir: _Path,
419
- build_lib: _Path,
420
- ):
421
- self.auxiliary_dir = Path(auxiliary_dir)
422
- self.build_lib = Path(build_lib).resolve()
423
- self._file = dist.get_command_obj("build_py").copy_file
424
- super().__init__(dist, name, [self.auxiliary_dir])
425
-
426
- def __call__(self, wheel: "WheelFile", files: List[str], mapping: Dict[str, str]):
427
- self._create_links(files, mapping)
428
- super().__call__(wheel, files, mapping)
429
-
430
- def _normalize_output(self, file: str) -> Optional[str]:
431
- # Files relative to build_lib will be normalized to None
432
- with suppress(ValueError):
433
- path = Path(file).resolve().relative_to(self.build_lib)
434
- return str(path).replace(os.sep, '/')
435
- return None
436
-
437
- def _create_file(self, relative_output: str, src_file: str, link=None):
438
- dest = self.auxiliary_dir / relative_output
439
- if not dest.parent.is_dir():
440
- dest.parent.mkdir(parents=True)
441
- self._file(src_file, dest, link=link)
442
-
443
- def _create_links(self, outputs, output_mapping):
444
- self.auxiliary_dir.mkdir(parents=True, exist_ok=True)
445
- link_type = "sym" if _can_symlink_files(self.auxiliary_dir) else "hard"
446
- mappings = {
447
- self._normalize_output(k): v
448
- for k, v in output_mapping.items()
449
- }
450
- mappings.pop(None, None) # remove files that are not relative to build_lib
451
-
452
- for output in outputs:
453
- relative = self._normalize_output(output)
454
- if relative and relative not in mappings:
455
- self._create_file(relative, output)
456
-
457
- for relative, src in mappings.items():
458
- self._create_file(relative, src, link=link_type)
459
-
460
- def __enter__(self):
461
- msg = "Strict editable install will be performed using a link tree.\n"
462
- _logger.warning(msg + _STRICT_WARNING)
463
- return self
464
-
465
- def __exit__(self, _exc_type, _exc_value, _traceback):
466
- msg = f"""\n
467
- Strict editable installation performed using the auxiliary directory:
468
- {self.auxiliary_dir}
469
-
470
- Please be careful to not remove this directory, otherwise you might not be able
471
- to import/use your package.
472
- """
473
- warnings.warn(msg, InformationOnly)
474
-
475
-
476
- class _TopLevelFinder:
477
- def __init__(self, dist: Distribution, name: str):
478
- self.dist = dist
479
- self.name = name
480
-
481
- def __call__(self, wheel: "WheelFile", files: List[str], mapping: Dict[str, str]):
482
- src_root = self.dist.src_root or os.curdir
483
- top_level = chain(_find_packages(self.dist), _find_top_level_modules(self.dist))
484
- package_dir = self.dist.package_dir or {}
485
- roots = _find_package_roots(top_level, package_dir, src_root)
486
-
487
- namespaces_: Dict[str, List[str]] = dict(chain(
488
- _find_namespaces(self.dist.packages or [], roots),
489
- ((ns, []) for ns in _find_virtual_namespaces(roots)),
490
- ))
491
-
492
- name = f"__editable__.{self.name}.finder"
493
- finder = _make_identifier(name)
494
- content = bytes(_finder_template(name, roots, namespaces_), "utf-8")
495
- wheel.writestr(f"{finder}.py", content)
496
-
497
- content = bytes(f"import {finder}; {finder}.install()", "utf-8")
498
- wheel.writestr(f"__editable__.{self.name}.pth", content)
499
-
500
- def __enter__(self):
501
- msg = "Editable install will be performed using a meta path finder.\n"
502
- _logger.warning(msg + _LENIENT_WARNING)
503
- return self
504
-
505
- def __exit__(self, _exc_type, _exc_value, _traceback):
506
- msg = """\n
507
- Please be careful with folders in your working directory with the same
508
- name as your package as they may take precedence during imports.
509
- """
510
- warnings.warn(msg, InformationOnly)
511
-
512
-
513
- def _can_symlink_files(base_dir: Path) -> bool:
514
- with TemporaryDirectory(dir=str(base_dir.resolve())) as tmp:
515
- path1, path2 = Path(tmp, "file1.txt"), Path(tmp, "file2.txt")
516
- path1.write_text("file1", encoding="utf-8")
517
- with suppress(AttributeError, NotImplementedError, OSError):
518
- os.symlink(path1, path2)
519
- if path2.is_symlink() and path2.read_text(encoding="utf-8") == "file1":
520
- return True
521
-
522
- try:
523
- os.link(path1, path2) # Ensure hard links can be created
524
- except Exception as ex:
525
- msg = (
526
- "File system does not seem to support either symlinks or hard links. "
527
- "Strict editable installs require one of them to be supported."
528
- )
529
- raise LinksNotSupported(msg) from ex
530
- return False
531
-
532
-
533
- def _simple_layout(
534
- packages: Iterable[str], package_dir: Dict[str, str], project_dir: Path
535
- ) -> bool:
536
- """Return ``True`` if:
537
- - all packages are contained by the same parent directory, **and**
538
- - all packages become importable if the parent directory is added to ``sys.path``.
539
-
540
- >>> _simple_layout(['a'], {"": "src"}, "/tmp/myproj")
541
- True
542
- >>> _simple_layout(['a', 'a.b'], {"": "src"}, "/tmp/myproj")
543
- True
544
- >>> _simple_layout(['a', 'a.b'], {}, "/tmp/myproj")
545
- True
546
- >>> _simple_layout(['a', 'a.a1', 'a.a1.a2', 'b'], {"": "src"}, "/tmp/myproj")
547
- True
548
- >>> _simple_layout(['a', 'a.a1', 'a.a1.a2', 'b'], {"a": "a", "b": "b"}, ".")
549
- True
550
- >>> _simple_layout(['a', 'a.a1', 'a.a1.a2', 'b'], {"a": "_a", "b": "_b"}, ".")
551
- False
552
- >>> _simple_layout(['a', 'a.a1', 'a.a1.a2', 'b'], {"a": "_a"}, "/tmp/myproj")
553
- False
554
- >>> _simple_layout(['a', 'a.a1', 'a.a1.a2', 'b'], {"a.a1.a2": "_a2"}, ".")
555
- False
556
- >>> _simple_layout(['a', 'a.b'], {"": "src", "a.b": "_ab"}, "/tmp/myproj")
557
- False
558
- >>> # Special cases, no packages yet:
559
- >>> _simple_layout([], {"": "src"}, "/tmp/myproj")
560
- True
561
- >>> _simple_layout([], {"a": "_a", "": "src"}, "/tmp/myproj")
562
- False
563
- """
564
- layout = {
565
- pkg: find_package_path(pkg, package_dir, project_dir)
566
- for pkg in packages
567
- }
568
- if not layout:
569
- return set(package_dir) in ({}, {""})
570
- parent = os.path.commonpath([_parent_path(k, v) for k, v in layout.items()])
571
- return all(
572
- _normalize_path(Path(parent, *key.split('.'))) == _normalize_path(value)
573
- for key, value in layout.items()
574
- )
575
-
576
-
577
- def _parent_path(pkg, pkg_path):
578
- """Infer the parent path containing a package, that if added to ``sys.path`` would
579
- allow importing that package.
580
- When ``pkg`` is directly mapped into a directory with a different name, return its
581
- own path.
582
- >>> _parent_path("a", "src/a")
583
- 'src'
584
- >>> _parent_path("b", "src/c")
585
- 'src/c'
586
- """
587
- parent = pkg_path[:-len(pkg)] if pkg_path.endswith(pkg) else pkg_path
588
- return parent.rstrip("/" + os.sep)
589
-
590
-
591
- def _find_packages(dist: Distribution) -> Iterator[str]:
592
- yield from iter(dist.packages or [])
593
-
594
- py_modules = dist.py_modules or []
595
- nested_modules = [mod for mod in py_modules if "." in mod]
596
- if dist.ext_package:
597
- yield dist.ext_package
598
- else:
599
- ext_modules = dist.ext_modules or []
600
- nested_modules += [x.name for x in ext_modules if "." in x.name]
601
-
602
- for module in nested_modules:
603
- package, _, _ = module.rpartition(".")
604
- yield package
605
-
606
-
607
- def _find_top_level_modules(dist: Distribution) -> Iterator[str]:
608
- py_modules = dist.py_modules or []
609
- yield from (mod for mod in py_modules if "." not in mod)
610
-
611
- if not dist.ext_package:
612
- ext_modules = dist.ext_modules or []
613
- yield from (x.name for x in ext_modules if "." not in x.name)
614
-
615
-
616
- def _find_package_roots(
617
- packages: Iterable[str],
618
- package_dir: Mapping[str, str],
619
- src_root: _Path,
620
- ) -> Dict[str, str]:
621
- pkg_roots: Dict[str, str] = {
622
- pkg: _absolute_root(find_package_path(pkg, package_dir, src_root))
623
- for pkg in sorted(packages)
624
- }
625
-
626
- return _remove_nested(pkg_roots)
627
-
628
-
629
- def _absolute_root(path: _Path) -> str:
630
- """Works for packages and top-level modules"""
631
- path_ = Path(path)
632
- parent = path_.parent
633
-
634
- if path_.exists():
635
- return str(path_.resolve())
636
- else:
637
- return str(parent.resolve() / path_.name)
638
-
639
-
640
- def _find_virtual_namespaces(pkg_roots: Dict[str, str]) -> Iterator[str]:
641
- """By carefully designing ``package_dir``, it is possible to implement the logical
642
- structure of PEP 420 in a package without the corresponding directories.
643
-
644
- Moreover a parent package can be purposefully/accidentally skipped in the discovery
645
- phase (e.g. ``find_packages(include=["mypkg.*"])``, when ``mypkg.foo`` is included
646
- by ``mypkg`` itself is not).
647
- We consider this case to also be a virtual namespace (ignoring the original
648
- directory) to emulate a non-editable installation.
649
-
650
- This function will try to find these kinds of namespaces.
651
- """
652
- for pkg in pkg_roots:
653
- if "." not in pkg:
654
- continue
655
- parts = pkg.split(".")
656
- for i in range(len(parts) - 1, 0, -1):
657
- partial_name = ".".join(parts[:i])
658
- path = Path(find_package_path(partial_name, pkg_roots, ""))
659
- if not path.exists() or partial_name not in pkg_roots:
660
- # partial_name not in pkg_roots ==> purposefully/accidentally skipped
661
- yield partial_name
662
-
663
-
664
- def _find_namespaces(
665
- packages: List[str], pkg_roots: Dict[str, str]
666
- ) -> Iterator[Tuple[str, List[str]]]:
667
- for pkg in packages:
668
- path = find_package_path(pkg, pkg_roots, "")
669
- if Path(path).exists() and not Path(path, "__init__.py").exists():
670
- yield (pkg, [path])
671
-
672
-
673
- def _remove_nested(pkg_roots: Dict[str, str]) -> Dict[str, str]:
674
- output = dict(pkg_roots.copy())
675
-
676
- for pkg, path in reversed(list(pkg_roots.items())):
677
- if any(
678
- pkg != other and _is_nested(pkg, path, other, other_path)
679
- for other, other_path in pkg_roots.items()
680
- ):
681
- output.pop(pkg)
682
-
683
- return output
684
-
685
-
686
- def _is_nested(pkg: str, pkg_path: str, parent: str, parent_path: str) -> bool:
687
- """
688
- Return ``True`` if ``pkg`` is nested inside ``parent`` both logically and in the
689
- file system.
690
- >>> _is_nested("a.b", "path/a/b", "a", "path/a")
691
- True
692
- >>> _is_nested("a.b", "path/a/b", "a", "otherpath/a")
693
- False
694
- >>> _is_nested("a.b", "path/a/b", "c", "path/c")
695
- False
696
- >>> _is_nested("a.a", "path/a/a", "a", "path/a")
697
- True
698
- >>> _is_nested("b.a", "path/b/a", "a", "path/a")
699
- False
700
- """
701
- norm_pkg_path = _normalize_path(pkg_path)
702
- rest = pkg.replace(parent, "", 1).strip(".").split(".")
703
- return (
704
- pkg.startswith(parent)
705
- and norm_pkg_path == _normalize_path(Path(parent_path, *rest))
706
- )
707
-
708
-
709
- def _normalize_path(filename: _Path) -> str:
710
- """Normalize a file/dir name for comparison purposes"""
711
- # See pkg_resources.normalize_path
712
- file = os.path.abspath(filename) if sys.platform == 'cygwin' else filename
713
- return os.path.normcase(os.path.realpath(os.path.normpath(file)))
714
-
715
-
716
- def _empty_dir(dir_: _P) -> _P:
717
- """Create a directory ensured to be empty. Existing files may be removed."""
718
- shutil.rmtree(dir_, ignore_errors=True)
719
- os.makedirs(dir_)
720
- return dir_
721
-
722
-
723
- def _make_identifier(name: str) -> str:
724
- """Make a string safe to be used as Python identifier.
725
- >>> _make_identifier("12abc")
726
- '_12abc'
727
- >>> _make_identifier("__editable__.myns.pkg-78.9.3_local")
728
- '__editable___myns_pkg_78_9_3_local'
729
- """
730
- safe = re.sub(r'\W|^(?=\d)', '_', name)
731
- assert safe.isidentifier()
732
- return safe
733
-
734
-
735
- class _NamespaceInstaller(namespaces.Installer):
736
- def __init__(self, distribution, installation_dir, editable_name, src_root):
737
- self.distribution = distribution
738
- self.src_root = src_root
739
- self.installation_dir = installation_dir
740
- self.editable_name = editable_name
741
- self.outputs = []
742
- self.dry_run = False
743
-
744
- def _get_target(self):
745
- """Installation target."""
746
- return os.path.join(self.installation_dir, self.editable_name)
747
-
748
- def _get_root(self):
749
- """Where the modules/packages should be loaded from."""
750
- return repr(str(self.src_root))
751
-
752
-
753
- _FINDER_TEMPLATE = """\
754
- import sys
755
- from importlib.machinery import ModuleSpec
756
- from importlib.machinery import all_suffixes as module_suffixes
757
- from importlib.util import spec_from_file_location
758
- from itertools import chain
759
- from pathlib import Path
760
-
761
- MAPPING = {mapping!r}
762
- NAMESPACES = {namespaces!r}
763
- PATH_PLACEHOLDER = {name!r} + ".__path_hook__"
764
-
765
-
766
- class _EditableFinder: # MetaPathFinder
767
- @classmethod
768
- def find_spec(cls, fullname, path=None, target=None):
769
- for pkg, pkg_path in reversed(list(MAPPING.items())):
770
- if fullname == pkg or fullname.startswith(f"{{pkg}}."):
771
- rest = fullname.replace(pkg, "", 1).strip(".").split(".")
772
- return cls._find_spec(fullname, Path(pkg_path, *rest))
773
-
774
- return None
775
-
776
- @classmethod
777
- def _find_spec(cls, fullname, candidate_path):
778
- init = candidate_path / "__init__.py"
779
- candidates = (candidate_path.with_suffix(x) for x in module_suffixes())
780
- for candidate in chain([init], candidates):
781
- if candidate.exists():
782
- return spec_from_file_location(fullname, candidate)
783
-
784
-
785
- class _EditableNamespaceFinder: # PathEntryFinder
786
- @classmethod
787
- def _path_hook(cls, path):
788
- if path == PATH_PLACEHOLDER:
789
- return cls
790
- raise ImportError
791
-
792
- @classmethod
793
- def _paths(cls, fullname):
794
- # Ensure __path__ is not empty for the spec to be considered a namespace.
795
- return NAMESPACES[fullname] or MAPPING.get(fullname) or [PATH_PLACEHOLDER]
796
-
797
- @classmethod
798
- def find_spec(cls, fullname, target=None):
799
- if fullname in NAMESPACES:
800
- spec = ModuleSpec(fullname, None, is_package=True)
801
- spec.submodule_search_locations = cls._paths(fullname)
802
- return spec
803
- return None
804
-
805
- @classmethod
806
- def find_module(cls, fullname):
807
- return None
808
-
809
-
810
- def install():
811
- if not any(finder == _EditableFinder for finder in sys.meta_path):
812
- sys.meta_path.append(_EditableFinder)
813
-
814
- if not NAMESPACES:
815
- return
816
-
817
- if not any(hook == _EditableNamespaceFinder._path_hook for hook in sys.path_hooks):
818
- # PathEntryFinder is needed to create NamespaceSpec without private APIS
819
- sys.path_hooks.append(_EditableNamespaceFinder._path_hook)
820
- if PATH_PLACEHOLDER not in sys.path:
821
- sys.path.append(PATH_PLACEHOLDER) # Used just to trigger the path hook
822
- """
823
-
824
-
825
- def _finder_template(
826
- name: str, mapping: Mapping[str, str], namespaces: Dict[str, List[str]]
827
- ) -> str:
828
- """Create a string containing the code for the``MetaPathFinder`` and
829
- ``PathEntryFinder``.
830
- """
831
- mapping = dict(sorted(mapping.items(), key=lambda p: p[0]))
832
- return _FINDER_TEMPLATE.format(name=name, mapping=mapping, namespaces=namespaces)
833
-
834
-
835
- class InformationOnly(UserWarning):
836
- """Currently there is no clear way of displaying messages to the users
837
- that use the setuptools backend directly via ``pip``.
838
- The only thing that might work is a warning, although it is not the
839
- most appropriate tool for the job...
840
- """
841
-
842
-
843
- class LinksNotSupported(errors.FileError):
844
- """File system does not seem to support either symlinks or hard links."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Bart92/RVC_HF/infer/lib/uvr5_pack/lib_v5/nets.py DELETED
@@ -1,123 +0,0 @@
1
- import layers
2
- import torch
3
- import torch.nn.functional as F
4
- from torch import nn
5
-
6
- from . import spec_utils
7
-
8
-
9
- class BaseASPPNet(nn.Module):
10
- def __init__(self, nin, ch, dilations=(4, 8, 16)):
11
- super(BaseASPPNet, self).__init__()
12
- self.enc1 = layers.Encoder(nin, ch, 3, 2, 1)
13
- self.enc2 = layers.Encoder(ch, ch * 2, 3, 2, 1)
14
- self.enc3 = layers.Encoder(ch * 2, ch * 4, 3, 2, 1)
15
- self.enc4 = layers.Encoder(ch * 4, ch * 8, 3, 2, 1)
16
-
17
- self.aspp = layers.ASPPModule(ch * 8, ch * 16, dilations)
18
-
19
- self.dec4 = layers.Decoder(ch * (8 + 16), ch * 8, 3, 1, 1)
20
- self.dec3 = layers.Decoder(ch * (4 + 8), ch * 4, 3, 1, 1)
21
- self.dec2 = layers.Decoder(ch * (2 + 4), ch * 2, 3, 1, 1)
22
- self.dec1 = layers.Decoder(ch * (1 + 2), ch, 3, 1, 1)
23
-
24
- def __call__(self, x):
25
- h, e1 = self.enc1(x)
26
- h, e2 = self.enc2(h)
27
- h, e3 = self.enc3(h)
28
- h, e4 = self.enc4(h)
29
-
30
- h = self.aspp(h)
31
-
32
- h = self.dec4(h, e4)
33
- h = self.dec3(h, e3)
34
- h = self.dec2(h, e2)
35
- h = self.dec1(h, e1)
36
-
37
- return h
38
-
39
-
40
- class CascadedASPPNet(nn.Module):
41
- def __init__(self, n_fft):
42
- super(CascadedASPPNet, self).__init__()
43
- self.stg1_low_band_net = BaseASPPNet(2, 16)
44
- self.stg1_high_band_net = BaseASPPNet(2, 16)
45
-
46
- self.stg2_bridge = layers.Conv2DBNActiv(18, 8, 1, 1, 0)
47
- self.stg2_full_band_net = BaseASPPNet(8, 16)
48
-
49
- self.stg3_bridge = layers.Conv2DBNActiv(34, 16, 1, 1, 0)
50
- self.stg3_full_band_net = BaseASPPNet(16, 32)
51
-
52
- self.out = nn.Conv2d(32, 2, 1, bias=False)
53
- self.aux1_out = nn.Conv2d(16, 2, 1, bias=False)
54
- self.aux2_out = nn.Conv2d(16, 2, 1, bias=False)
55
-
56
- self.max_bin = n_fft // 2
57
- self.output_bin = n_fft // 2 + 1
58
-
59
- self.offset = 128
60
-
61
- def forward(self, x, aggressiveness=None):
62
- mix = x.detach()
63
- x = x.clone()
64
-
65
- x = x[:, :, : self.max_bin]
66
-
67
- bandw = x.size()[2] // 2
68
- aux1 = torch.cat(
69
- [
70
- self.stg1_low_band_net(x[:, :, :bandw]),
71
- self.stg1_high_band_net(x[:, :, bandw:]),
72
- ],
73
- dim=2,
74
- )
75
-
76
- h = torch.cat([x, aux1], dim=1)
77
- aux2 = self.stg2_full_band_net(self.stg2_bridge(h))
78
-
79
- h = torch.cat([x, aux1, aux2], dim=1)
80
- h = self.stg3_full_band_net(self.stg3_bridge(h))
81
-
82
- mask = torch.sigmoid(self.out(h))
83
- mask = F.pad(
84
- input=mask,
85
- pad=(0, 0, 0, self.output_bin - mask.size()[2]),
86
- mode="replicate",
87
- )
88
-
89
- if self.training:
90
- aux1 = torch.sigmoid(self.aux1_out(aux1))
91
- aux1 = F.pad(
92
- input=aux1,
93
- pad=(0, 0, 0, self.output_bin - aux1.size()[2]),
94
- mode="replicate",
95
- )
96
- aux2 = torch.sigmoid(self.aux2_out(aux2))
97
- aux2 = F.pad(
98
- input=aux2,
99
- pad=(0, 0, 0, self.output_bin - aux2.size()[2]),
100
- mode="replicate",
101
- )
102
- return mask * mix, aux1 * mix, aux2 * mix
103
- else:
104
- if aggressiveness:
105
- mask[:, :, : aggressiveness["split_bin"]] = torch.pow(
106
- mask[:, :, : aggressiveness["split_bin"]],
107
- 1 + aggressiveness["value"] / 3,
108
- )
109
- mask[:, :, aggressiveness["split_bin"] :] = torch.pow(
110
- mask[:, :, aggressiveness["split_bin"] :],
111
- 1 + aggressiveness["value"],
112
- )
113
-
114
- return mask * mix
115
-
116
- def predict(self, x_mag, aggressiveness=None):
117
- h = self.forward(x_mag, aggressiveness)
118
-
119
- if self.offset > 0:
120
- h = h[:, :, :, self.offset : -self.offset]
121
- assert h.size()[3] > 0
122
-
123
- return h
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Bart92/RVC_HF/lib/infer_pack/models_dml.py DELETED
@@ -1,1124 +0,0 @@
1
- import math, pdb, os
2
- from time import time as ttime
3
- import torch
4
- from torch import nn
5
- from torch.nn import functional as F
6
- from lib.infer_pack import modules
7
- from lib.infer_pack import attentions
8
- from lib.infer_pack import commons
9
- from lib.infer_pack.commons import init_weights, get_padding
10
- from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
11
- from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
12
- from lib.infer_pack.commons import init_weights
13
- import numpy as np
14
- from lib.infer_pack import commons
15
-
16
-
17
- class TextEncoder256(nn.Module):
18
- def __init__(
19
- self,
20
- out_channels,
21
- hidden_channels,
22
- filter_channels,
23
- n_heads,
24
- n_layers,
25
- kernel_size,
26
- p_dropout,
27
- f0=True,
28
- ):
29
- super().__init__()
30
- self.out_channels = out_channels
31
- self.hidden_channels = hidden_channels
32
- self.filter_channels = filter_channels
33
- self.n_heads = n_heads
34
- self.n_layers = n_layers
35
- self.kernel_size = kernel_size
36
- self.p_dropout = p_dropout
37
- self.emb_phone = nn.Linear(256, hidden_channels)
38
- self.lrelu = nn.LeakyReLU(0.1, inplace=True)
39
- if f0 == True:
40
- self.emb_pitch = nn.Embedding(256, hidden_channels) # pitch 256
41
- self.encoder = attentions.Encoder(
42
- hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout
43
- )
44
- self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
45
-
46
- def forward(self, phone, pitch, lengths):
47
- if pitch == None:
48
- x = self.emb_phone(phone)
49
- else:
50
- x = self.emb_phone(phone) + self.emb_pitch(pitch)
51
- x = x * math.sqrt(self.hidden_channels) # [b, t, h]
52
- x = self.lrelu(x)
53
- x = torch.transpose(x, 1, -1) # [b, h, t]
54
- x_mask = torch.unsqueeze(commons.sequence_mask(lengths, x.size(2)), 1).to(
55
- x.dtype
56
- )
57
- x = self.encoder(x * x_mask, x_mask)
58
- stats = self.proj(x) * x_mask
59
-
60
- m, logs = torch.split(stats, self.out_channels, dim=1)
61
- return m, logs, x_mask
62
-
63
-
64
- class TextEncoder768(nn.Module):
65
- def __init__(
66
- self,
67
- out_channels,
68
- hidden_channels,
69
- filter_channels,
70
- n_heads,
71
- n_layers,
72
- kernel_size,
73
- p_dropout,
74
- f0=True,
75
- ):
76
- super().__init__()
77
- self.out_channels = out_channels
78
- self.hidden_channels = hidden_channels
79
- self.filter_channels = filter_channels
80
- self.n_heads = n_heads
81
- self.n_layers = n_layers
82
- self.kernel_size = kernel_size
83
- self.p_dropout = p_dropout
84
- self.emb_phone = nn.Linear(768, hidden_channels)
85
- self.lrelu = nn.LeakyReLU(0.1, inplace=True)
86
- if f0 == True:
87
- self.emb_pitch = nn.Embedding(256, hidden_channels) # pitch 256
88
- self.encoder = attentions.Encoder(
89
- hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout
90
- )
91
- self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
92
-
93
- def forward(self, phone, pitch, lengths):
94
- if pitch == None:
95
- x = self.emb_phone(phone)
96
- else:
97
- x = self.emb_phone(phone) + self.emb_pitch(pitch)
98
- x = x * math.sqrt(self.hidden_channels) # [b, t, h]
99
- x = self.lrelu(x)
100
- x = torch.transpose(x, 1, -1) # [b, h, t]
101
- x_mask = torch.unsqueeze(commons.sequence_mask(lengths, x.size(2)), 1).to(
102
- x.dtype
103
- )
104
- x = self.encoder(x * x_mask, x_mask)
105
- stats = self.proj(x) * x_mask
106
-
107
- m, logs = torch.split(stats, self.out_channels, dim=1)
108
- return m, logs, x_mask
109
-
110
-
111
- class ResidualCouplingBlock(nn.Module):
112
- def __init__(
113
- self,
114
- channels,
115
- hidden_channels,
116
- kernel_size,
117
- dilation_rate,
118
- n_layers,
119
- n_flows=4,
120
- gin_channels=0,
121
- ):
122
- super().__init__()
123
- self.channels = channels
124
- self.hidden_channels = hidden_channels
125
- self.kernel_size = kernel_size
126
- self.dilation_rate = dilation_rate
127
- self.n_layers = n_layers
128
- self.n_flows = n_flows
129
- self.gin_channels = gin_channels
130
-
131
- self.flows = nn.ModuleList()
132
- for i in range(n_flows):
133
- self.flows.append(
134
- modules.ResidualCouplingLayer(
135
- channels,
136
- hidden_channels,
137
- kernel_size,
138
- dilation_rate,
139
- n_layers,
140
- gin_channels=gin_channels,
141
- mean_only=True,
142
- )
143
- )
144
- self.flows.append(modules.Flip())
145
-
146
- def forward(self, x, x_mask, g=None, reverse=False):
147
- if not reverse:
148
- for flow in self.flows:
149
- x, _ = flow(x, x_mask, g=g, reverse=reverse)
150
- else:
151
- for flow in reversed(self.flows):
152
- x = flow(x, x_mask, g=g, reverse=reverse)
153
- return x
154
-
155
- def remove_weight_norm(self):
156
- for i in range(self.n_flows):
157
- self.flows[i * 2].remove_weight_norm()
158
-
159
-
160
- class PosteriorEncoder(nn.Module):
161
- def __init__(
162
- self,
163
- in_channels,
164
- out_channels,
165
- hidden_channels,
166
- kernel_size,
167
- dilation_rate,
168
- n_layers,
169
- gin_channels=0,
170
- ):
171
- super().__init__()
172
- self.in_channels = in_channels
173
- self.out_channels = out_channels
174
- self.hidden_channels = hidden_channels
175
- self.kernel_size = kernel_size
176
- self.dilation_rate = dilation_rate
177
- self.n_layers = n_layers
178
- self.gin_channels = gin_channels
179
-
180
- self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
181
- self.enc = modules.WN(
182
- hidden_channels,
183
- kernel_size,
184
- dilation_rate,
185
- n_layers,
186
- gin_channels=gin_channels,
187
- )
188
- self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
189
-
190
- def forward(self, x, x_lengths, g=None):
191
- x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(
192
- x.dtype
193
- )
194
- x = self.pre(x) * x_mask
195
- x = self.enc(x, x_mask, g=g)
196
- stats = self.proj(x) * x_mask
197
- m, logs = torch.split(stats, self.out_channels, dim=1)
198
- z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
199
- return z, m, logs, x_mask
200
-
201
- def remove_weight_norm(self):
202
- self.enc.remove_weight_norm()
203
-
204
-
205
- class Generator(torch.nn.Module):
206
- def __init__(
207
- self,
208
- initial_channel,
209
- resblock,
210
- resblock_kernel_sizes,
211
- resblock_dilation_sizes,
212
- upsample_rates,
213
- upsample_initial_channel,
214
- upsample_kernel_sizes,
215
- gin_channels=0,
216
- ):
217
- super(Generator, self).__init__()
218
- self.num_kernels = len(resblock_kernel_sizes)
219
- self.num_upsamples = len(upsample_rates)
220
- self.conv_pre = Conv1d(
221
- initial_channel, upsample_initial_channel, 7, 1, padding=3
222
- )
223
- resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2
224
-
225
- self.ups = nn.ModuleList()
226
- for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
227
- self.ups.append(
228
- weight_norm(
229
- ConvTranspose1d(
230
- upsample_initial_channel // (2**i),
231
- upsample_initial_channel // (2 ** (i + 1)),
232
- k,
233
- u,
234
- padding=(k - u) // 2,
235
- )
236
- )
237
- )
238
-
239
- self.resblocks = nn.ModuleList()
240
- for i in range(len(self.ups)):
241
- ch = upsample_initial_channel // (2 ** (i + 1))
242
- for j, (k, d) in enumerate(
243
- zip(resblock_kernel_sizes, resblock_dilation_sizes)
244
- ):
245
- self.resblocks.append(resblock(ch, k, d))
246
-
247
- self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
248
- self.ups.apply(init_weights)
249
-
250
- if gin_channels != 0:
251
- self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
252
-
253
- def forward(self, x, g=None):
254
- x = self.conv_pre(x)
255
- if g is not None:
256
- x = x + self.cond(g)
257
-
258
- for i in range(self.num_upsamples):
259
- x = F.leaky_relu(x, modules.LRELU_SLOPE)
260
- x = self.ups[i](x)
261
- xs = None
262
- for j in range(self.num_kernels):
263
- if xs is None:
264
- xs = self.resblocks[i * self.num_kernels + j](x)
265
- else:
266
- xs += self.resblocks[i * self.num_kernels + j](x)
267
- x = xs / self.num_kernels
268
- x = F.leaky_relu(x)
269
- x = self.conv_post(x)
270
- x = torch.tanh(x)
271
-
272
- return x
273
-
274
- def remove_weight_norm(self):
275
- for l in self.ups:
276
- remove_weight_norm(l)
277
- for l in self.resblocks:
278
- l.remove_weight_norm()
279
-
280
-
281
- class SineGen(torch.nn.Module):
282
- """Definition of sine generator
283
- SineGen(samp_rate, harmonic_num = 0,
284
- sine_amp = 0.1, noise_std = 0.003,
285
- voiced_threshold = 0,
286
- flag_for_pulse=False)
287
- samp_rate: sampling rate in Hz
288
- harmonic_num: number of harmonic overtones (default 0)
289
- sine_amp: amplitude of sine-wavefrom (default 0.1)
290
- noise_std: std of Gaussian noise (default 0.003)
291
- voiced_thoreshold: F0 threshold for U/V classification (default 0)
292
- flag_for_pulse: this SinGen is used inside PulseGen (default False)
293
- Note: when flag_for_pulse is True, the first time step of a voiced
294
- segment is always sin(np.pi) or cos(0)
295
- """
296
-
297
- def __init__(
298
- self,
299
- samp_rate,
300
- harmonic_num=0,
301
- sine_amp=0.1,
302
- noise_std=0.003,
303
- voiced_threshold=0,
304
- flag_for_pulse=False,
305
- ):
306
- super(SineGen, self).__init__()
307
- self.sine_amp = sine_amp
308
- self.noise_std = noise_std
309
- self.harmonic_num = harmonic_num
310
- self.dim = self.harmonic_num + 1
311
- self.sampling_rate = samp_rate
312
- self.voiced_threshold = voiced_threshold
313
-
314
- def _f02uv(self, f0):
315
- # generate uv signal
316
- uv = torch.ones_like(f0)
317
- uv = uv * (f0 > self.voiced_threshold)
318
- return uv.float()
319
-
320
- def forward(self, f0, upp):
321
- """sine_tensor, uv = forward(f0)
322
- input F0: tensor(batchsize=1, length, dim=1)
323
- f0 for unvoiced steps should be 0
324
- output sine_tensor: tensor(batchsize=1, length, dim)
325
- output uv: tensor(batchsize=1, length, 1)
326
- """
327
- with torch.no_grad():
328
- f0 = f0[:, None].transpose(1, 2)
329
- f0_buf = torch.zeros(f0.shape[0], f0.shape[1], self.dim, device=f0.device)
330
- # fundamental component
331
- f0_buf[:, :, 0] = f0[:, :, 0]
332
- for idx in np.arange(self.harmonic_num):
333
- f0_buf[:, :, idx + 1] = f0_buf[:, :, 0] * (
334
- idx + 2
335
- ) # idx + 2: the (idx+1)-th overtone, (idx+2)-th harmonic
336
- rad_values = (f0_buf / self.sampling_rate) % 1 ###%1意味着n_har的乘积无法后处理优化
337
- rand_ini = torch.rand(
338
- f0_buf.shape[0], f0_buf.shape[2], device=f0_buf.device
339
- )
340
- rand_ini[:, 0] = 0
341
- rad_values[:, 0, :] = rad_values[:, 0, :] + rand_ini
342
- tmp_over_one = torch.cumsum(rad_values, 1) # % 1 #####%1意味着后面的cumsum无法再优化
343
- tmp_over_one *= upp
344
- tmp_over_one = F.interpolate(
345
- tmp_over_one.transpose(2, 1),
346
- scale_factor=upp,
347
- mode="linear",
348
- align_corners=True,
349
- ).transpose(2, 1)
350
- rad_values = F.interpolate(
351
- rad_values.transpose(2, 1), scale_factor=upp, mode="nearest"
352
- ).transpose(
353
- 2, 1
354
- ) #######
355
- tmp_over_one %= 1
356
- tmp_over_one_idx = (tmp_over_one[:, 1:, :] - tmp_over_one[:, :-1, :]) < 0
357
- cumsum_shift = torch.zeros_like(rad_values)
358
- cumsum_shift[:, 1:, :] = tmp_over_one_idx * -1.0
359
- sine_waves = torch.sin(
360
- torch.cumsum(rad_values + cumsum_shift, dim=1) * 2 * np.pi
361
- )
362
- sine_waves = sine_waves * self.sine_amp
363
- uv = self._f02uv(f0)
364
- uv = F.interpolate(
365
- uv.transpose(2, 1), scale_factor=upp, mode="nearest"
366
- ).transpose(2, 1)
367
- noise_amp = uv * self.noise_std + (1 - uv) * self.sine_amp / 3
368
- noise = noise_amp * torch.randn_like(sine_waves)
369
- sine_waves = sine_waves * uv + noise
370
- return sine_waves, uv, noise
371
-
372
-
373
- class SourceModuleHnNSF(torch.nn.Module):
374
- """SourceModule for hn-nsf
375
- SourceModule(sampling_rate, harmonic_num=0, sine_amp=0.1,
376
- add_noise_std=0.003, voiced_threshod=0)
377
- sampling_rate: sampling_rate in Hz
378
- harmonic_num: number of harmonic above F0 (default: 0)
379
- sine_amp: amplitude of sine source signal (default: 0.1)
380
- add_noise_std: std of additive Gaussian noise (default: 0.003)
381
- note that amplitude of noise in unvoiced is decided
382
- by sine_amp
383
- voiced_threshold: threhold to set U/V given F0 (default: 0)
384
- Sine_source, noise_source = SourceModuleHnNSF(F0_sampled)
385
- F0_sampled (batchsize, length, 1)
386
- Sine_source (batchsize, length, 1)
387
- noise_source (batchsize, length 1)
388
- uv (batchsize, length, 1)
389
- """
390
-
391
- def __init__(
392
- self,
393
- sampling_rate,
394
- harmonic_num=0,
395
- sine_amp=0.1,
396
- add_noise_std=0.003,
397
- voiced_threshod=0,
398
- is_half=True,
399
- ):
400
- super(SourceModuleHnNSF, self).__init__()
401
-
402
- self.sine_amp = sine_amp
403
- self.noise_std = add_noise_std
404
- self.is_half = is_half
405
- # to produce sine waveforms
406
- self.l_sin_gen = SineGen(
407
- sampling_rate, harmonic_num, sine_amp, add_noise_std, voiced_threshod
408
- )
409
-
410
- # to merge source harmonics into a single excitation
411
- self.l_linear = torch.nn.Linear(harmonic_num + 1, 1)
412
- self.l_tanh = torch.nn.Tanh()
413
-
414
- def forward(self, x, upp=None):
415
- sine_wavs, uv, _ = self.l_sin_gen(x, upp)
416
- if self.is_half:
417
- sine_wavs = sine_wavs.half()
418
- sine_merge = self.l_tanh(self.l_linear(sine_wavs))
419
- return sine_merge, None, None # noise, uv
420
-
421
-
422
- class GeneratorNSF(torch.nn.Module):
423
- def __init__(
424
- self,
425
- initial_channel,
426
- resblock,
427
- resblock_kernel_sizes,
428
- resblock_dilation_sizes,
429
- upsample_rates,
430
- upsample_initial_channel,
431
- upsample_kernel_sizes,
432
- gin_channels,
433
- sr,
434
- is_half=False,
435
- ):
436
- super(GeneratorNSF, self).__init__()
437
- self.num_kernels = len(resblock_kernel_sizes)
438
- self.num_upsamples = len(upsample_rates)
439
-
440
- self.f0_upsamp = torch.nn.Upsample(scale_factor=np.prod(upsample_rates))
441
- self.m_source = SourceModuleHnNSF(
442
- sampling_rate=sr, harmonic_num=0, is_half=is_half
443
- )
444
- self.noise_convs = nn.ModuleList()
445
- self.conv_pre = Conv1d(
446
- initial_channel, upsample_initial_channel, 7, 1, padding=3
447
- )
448
- resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2
449
-
450
- self.ups = nn.ModuleList()
451
- for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
452
- c_cur = upsample_initial_channel // (2 ** (i + 1))
453
- self.ups.append(
454
- weight_norm(
455
- ConvTranspose1d(
456
- upsample_initial_channel // (2**i),
457
- upsample_initial_channel // (2 ** (i + 1)),
458
- k,
459
- u,
460
- padding=(k - u) // 2,
461
- )
462
- )
463
- )
464
- if i + 1 < len(upsample_rates):
465
- stride_f0 = np.prod(upsample_rates[i + 1 :])
466
- self.noise_convs.append(
467
- Conv1d(
468
- 1,
469
- c_cur,
470
- kernel_size=stride_f0 * 2,
471
- stride=stride_f0,
472
- padding=stride_f0 // 2,
473
- )
474
- )
475
- else:
476
- self.noise_convs.append(Conv1d(1, c_cur, kernel_size=1))
477
-
478
- self.resblocks = nn.ModuleList()
479
- for i in range(len(self.ups)):
480
- ch = upsample_initial_channel // (2 ** (i + 1))
481
- for j, (k, d) in enumerate(
482
- zip(resblock_kernel_sizes, resblock_dilation_sizes)
483
- ):
484
- self.resblocks.append(resblock(ch, k, d))
485
-
486
- self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
487
- self.ups.apply(init_weights)
488
-
489
- if gin_channels != 0:
490
- self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
491
-
492
- self.upp = np.prod(upsample_rates)
493
-
494
- def forward(self, x, f0, g=None):
495
- har_source, noi_source, uv = self.m_source(f0, self.upp)
496
- har_source = har_source.transpose(1, 2)
497
- x = self.conv_pre(x)
498
- if g is not None:
499
- x = x + self.cond(g)
500
-
501
- for i in range(self.num_upsamples):
502
- x = F.leaky_relu(x, modules.LRELU_SLOPE)
503
- x = self.ups[i](x)
504
- x_source = self.noise_convs[i](har_source)
505
- x = x + x_source
506
- xs = None
507
- for j in range(self.num_kernels):
508
- if xs is None:
509
- xs = self.resblocks[i * self.num_kernels + j](x)
510
- else:
511
- xs += self.resblocks[i * self.num_kernels + j](x)
512
- x = xs / self.num_kernels
513
- x = F.leaky_relu(x)
514
- x = self.conv_post(x)
515
- x = torch.tanh(x)
516
- return x
517
-
518
- def remove_weight_norm(self):
519
- for l in self.ups:
520
- remove_weight_norm(l)
521
- for l in self.resblocks:
522
- l.remove_weight_norm()
523
-
524
-
525
- sr2sr = {
526
- "32k": 32000,
527
- "40k": 40000,
528
- "48k": 48000,
529
- }
530
-
531
-
532
- class SynthesizerTrnMs256NSFsid(nn.Module):
533
- def __init__(
534
- self,
535
- spec_channels,
536
- segment_size,
537
- inter_channels,
538
- hidden_channels,
539
- filter_channels,
540
- n_heads,
541
- n_layers,
542
- kernel_size,
543
- p_dropout,
544
- resblock,
545
- resblock_kernel_sizes,
546
- resblock_dilation_sizes,
547
- upsample_rates,
548
- upsample_initial_channel,
549
- upsample_kernel_sizes,
550
- spk_embed_dim,
551
- gin_channels,
552
- sr,
553
- **kwargs
554
- ):
555
- super().__init__()
556
- if type(sr) == type("strr"):
557
- sr = sr2sr[sr]
558
- self.spec_channels = spec_channels
559
- self.inter_channels = inter_channels
560
- self.hidden_channels = hidden_channels
561
- self.filter_channels = filter_channels
562
- self.n_heads = n_heads
563
- self.n_layers = n_layers
564
- self.kernel_size = kernel_size
565
- self.p_dropout = p_dropout
566
- self.resblock = resblock
567
- self.resblock_kernel_sizes = resblock_kernel_sizes
568
- self.resblock_dilation_sizes = resblock_dilation_sizes
569
- self.upsample_rates = upsample_rates
570
- self.upsample_initial_channel = upsample_initial_channel
571
- self.upsample_kernel_sizes = upsample_kernel_sizes
572
- self.segment_size = segment_size
573
- self.gin_channels = gin_channels
574
- # self.hop_length = hop_length#
575
- self.spk_embed_dim = spk_embed_dim
576
- self.enc_p = TextEncoder256(
577
- inter_channels,
578
- hidden_channels,
579
- filter_channels,
580
- n_heads,
581
- n_layers,
582
- kernel_size,
583
- p_dropout,
584
- )
585
- self.dec = GeneratorNSF(
586
- inter_channels,
587
- resblock,
588
- resblock_kernel_sizes,
589
- resblock_dilation_sizes,
590
- upsample_rates,
591
- upsample_initial_channel,
592
- upsample_kernel_sizes,
593
- gin_channels=gin_channels,
594
- sr=sr,
595
- is_half=kwargs["is_half"],
596
- )
597
- self.enc_q = PosteriorEncoder(
598
- spec_channels,
599
- inter_channels,
600
- hidden_channels,
601
- 5,
602
- 1,
603
- 16,
604
- gin_channels=gin_channels,
605
- )
606
- self.flow = ResidualCouplingBlock(
607
- inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels
608
- )
609
- self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)
610
- print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim)
611
-
612
- def remove_weight_norm(self):
613
- self.dec.remove_weight_norm()
614
- self.flow.remove_weight_norm()
615
- self.enc_q.remove_weight_norm()
616
-
617
- def forward(
618
- self, phone, phone_lengths, pitch, pitchf, y, y_lengths, ds
619
- ): # 这里ds是id,[bs,1]
620
- # print(1,pitch.shape)#[bs,t]
621
- g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的
622
- m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths)
623
- z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
624
- z_p = self.flow(z, y_mask, g=g)
625
- z_slice, ids_slice = commons.rand_slice_segments(
626
- z, y_lengths, self.segment_size
627
- )
628
- # print(-1,pitchf.shape,ids_slice,self.segment_size,self.hop_length,self.segment_size//self.hop_length)
629
- pitchf = commons.slice_segments2(pitchf, ids_slice, self.segment_size)
630
- # print(-2,pitchf.shape,z_slice.shape)
631
- o = self.dec(z_slice, pitchf, g=g)
632
- return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q)
633
-
634
- def infer(self, phone, phone_lengths, pitch, nsff0, sid, max_len=None):
635
- g = self.emb_g(sid).unsqueeze(-1)
636
- m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths)
637
- z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask
638
- z = self.flow(z_p, x_mask, g=g, reverse=True)
639
- o = self.dec((z * x_mask)[:, :, :max_len], nsff0, g=g)
640
- return o, x_mask, (z, z_p, m_p, logs_p)
641
-
642
-
643
- class SynthesizerTrnMs768NSFsid(nn.Module):
644
- def __init__(
645
- self,
646
- spec_channels,
647
- segment_size,
648
- inter_channels,
649
- hidden_channels,
650
- filter_channels,
651
- n_heads,
652
- n_layers,
653
- kernel_size,
654
- p_dropout,
655
- resblock,
656
- resblock_kernel_sizes,
657
- resblock_dilation_sizes,
658
- upsample_rates,
659
- upsample_initial_channel,
660
- upsample_kernel_sizes,
661
- spk_embed_dim,
662
- gin_channels,
663
- sr,
664
- **kwargs
665
- ):
666
- super().__init__()
667
- if type(sr) == type("strr"):
668
- sr = sr2sr[sr]
669
- self.spec_channels = spec_channels
670
- self.inter_channels = inter_channels
671
- self.hidden_channels = hidden_channels
672
- self.filter_channels = filter_channels
673
- self.n_heads = n_heads
674
- self.n_layers = n_layers
675
- self.kernel_size = kernel_size
676
- self.p_dropout = p_dropout
677
- self.resblock = resblock
678
- self.resblock_kernel_sizes = resblock_kernel_sizes
679
- self.resblock_dilation_sizes = resblock_dilation_sizes
680
- self.upsample_rates = upsample_rates
681
- self.upsample_initial_channel = upsample_initial_channel
682
- self.upsample_kernel_sizes = upsample_kernel_sizes
683
- self.segment_size = segment_size
684
- self.gin_channels = gin_channels
685
- # self.hop_length = hop_length#
686
- self.spk_embed_dim = spk_embed_dim
687
- self.enc_p = TextEncoder768(
688
- inter_channels,
689
- hidden_channels,
690
- filter_channels,
691
- n_heads,
692
- n_layers,
693
- kernel_size,
694
- p_dropout,
695
- )
696
- self.dec = GeneratorNSF(
697
- inter_channels,
698
- resblock,
699
- resblock_kernel_sizes,
700
- resblock_dilation_sizes,
701
- upsample_rates,
702
- upsample_initial_channel,
703
- upsample_kernel_sizes,
704
- gin_channels=gin_channels,
705
- sr=sr,
706
- is_half=kwargs["is_half"],
707
- )
708
- self.enc_q = PosteriorEncoder(
709
- spec_channels,
710
- inter_channels,
711
- hidden_channels,
712
- 5,
713
- 1,
714
- 16,
715
- gin_channels=gin_channels,
716
- )
717
- self.flow = ResidualCouplingBlock(
718
- inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels
719
- )
720
- self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)
721
- print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim)
722
-
723
- def remove_weight_norm(self):
724
- self.dec.remove_weight_norm()
725
- self.flow.remove_weight_norm()
726
- self.enc_q.remove_weight_norm()
727
-
728
- def forward(
729
- self, phone, phone_lengths, pitch, pitchf, y, y_lengths, ds
730
- ): # 这里ds是id,[bs,1]
731
- # print(1,pitch.shape)#[bs,t]
732
- g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的
733
- m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths)
734
- z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
735
- z_p = self.flow(z, y_mask, g=g)
736
- z_slice, ids_slice = commons.rand_slice_segments(
737
- z, y_lengths, self.segment_size
738
- )
739
- # print(-1,pitchf.shape,ids_slice,self.segment_size,self.hop_length,self.segment_size//self.hop_length)
740
- pitchf = commons.slice_segments2(pitchf, ids_slice, self.segment_size)
741
- # print(-2,pitchf.shape,z_slice.shape)
742
- o = self.dec(z_slice, pitchf, g=g)
743
- return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q)
744
-
745
- def infer(self, phone, phone_lengths, pitch, nsff0, sid, max_len=None):
746
- g = self.emb_g(sid).unsqueeze(-1)
747
- m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths)
748
- z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask
749
- z = self.flow(z_p, x_mask, g=g, reverse=True)
750
- o = self.dec((z * x_mask)[:, :, :max_len], nsff0, g=g)
751
- return o, x_mask, (z, z_p, m_p, logs_p)
752
-
753
-
754
- class SynthesizerTrnMs256NSFsid_nono(nn.Module):
755
- def __init__(
756
- self,
757
- spec_channels,
758
- segment_size,
759
- inter_channels,
760
- hidden_channels,
761
- filter_channels,
762
- n_heads,
763
- n_layers,
764
- kernel_size,
765
- p_dropout,
766
- resblock,
767
- resblock_kernel_sizes,
768
- resblock_dilation_sizes,
769
- upsample_rates,
770
- upsample_initial_channel,
771
- upsample_kernel_sizes,
772
- spk_embed_dim,
773
- gin_channels,
774
- sr=None,
775
- **kwargs
776
- ):
777
- super().__init__()
778
- self.spec_channels = spec_channels
779
- self.inter_channels = inter_channels
780
- self.hidden_channels = hidden_channels
781
- self.filter_channels = filter_channels
782
- self.n_heads = n_heads
783
- self.n_layers = n_layers
784
- self.kernel_size = kernel_size
785
- self.p_dropout = p_dropout
786
- self.resblock = resblock
787
- self.resblock_kernel_sizes = resblock_kernel_sizes
788
- self.resblock_dilation_sizes = resblock_dilation_sizes
789
- self.upsample_rates = upsample_rates
790
- self.upsample_initial_channel = upsample_initial_channel
791
- self.upsample_kernel_sizes = upsample_kernel_sizes
792
- self.segment_size = segment_size
793
- self.gin_channels = gin_channels
794
- # self.hop_length = hop_length#
795
- self.spk_embed_dim = spk_embed_dim
796
- self.enc_p = TextEncoder256(
797
- inter_channels,
798
- hidden_channels,
799
- filter_channels,
800
- n_heads,
801
- n_layers,
802
- kernel_size,
803
- p_dropout,
804
- f0=False,
805
- )
806
- self.dec = Generator(
807
- inter_channels,
808
- resblock,
809
- resblock_kernel_sizes,
810
- resblock_dilation_sizes,
811
- upsample_rates,
812
- upsample_initial_channel,
813
- upsample_kernel_sizes,
814
- gin_channels=gin_channels,
815
- )
816
- self.enc_q = PosteriorEncoder(
817
- spec_channels,
818
- inter_channels,
819
- hidden_channels,
820
- 5,
821
- 1,
822
- 16,
823
- gin_channels=gin_channels,
824
- )
825
- self.flow = ResidualCouplingBlock(
826
- inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels
827
- )
828
- self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)
829
- print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim)
830
-
831
- def remove_weight_norm(self):
832
- self.dec.remove_weight_norm()
833
- self.flow.remove_weight_norm()
834
- self.enc_q.remove_weight_norm()
835
-
836
- def forward(self, phone, phone_lengths, y, y_lengths, ds): # 这里ds是id,[bs,1]
837
- g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的
838
- m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths)
839
- z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
840
- z_p = self.flow(z, y_mask, g=g)
841
- z_slice, ids_slice = commons.rand_slice_segments(
842
- z, y_lengths, self.segment_size
843
- )
844
- o = self.dec(z_slice, g=g)
845
- return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q)
846
-
847
- def infer(self, phone, phone_lengths, sid, max_len=None):
848
- g = self.emb_g(sid).unsqueeze(-1)
849
- m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths)
850
- z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask
851
- z = self.flow(z_p, x_mask, g=g, reverse=True)
852
- o = self.dec((z * x_mask)[:, :, :max_len], g=g)
853
- return o, x_mask, (z, z_p, m_p, logs_p)
854
-
855
-
856
- class SynthesizerTrnMs768NSFsid_nono(nn.Module):
857
- def __init__(
858
- self,
859
- spec_channels,
860
- segment_size,
861
- inter_channels,
862
- hidden_channels,
863
- filter_channels,
864
- n_heads,
865
- n_layers,
866
- kernel_size,
867
- p_dropout,
868
- resblock,
869
- resblock_kernel_sizes,
870
- resblock_dilation_sizes,
871
- upsample_rates,
872
- upsample_initial_channel,
873
- upsample_kernel_sizes,
874
- spk_embed_dim,
875
- gin_channels,
876
- sr=None,
877
- **kwargs
878
- ):
879
- super().__init__()
880
- self.spec_channels = spec_channels
881
- self.inter_channels = inter_channels
882
- self.hidden_channels = hidden_channels
883
- self.filter_channels = filter_channels
884
- self.n_heads = n_heads
885
- self.n_layers = n_layers
886
- self.kernel_size = kernel_size
887
- self.p_dropout = p_dropout
888
- self.resblock = resblock
889
- self.resblock_kernel_sizes = resblock_kernel_sizes
890
- self.resblock_dilation_sizes = resblock_dilation_sizes
891
- self.upsample_rates = upsample_rates
892
- self.upsample_initial_channel = upsample_initial_channel
893
- self.upsample_kernel_sizes = upsample_kernel_sizes
894
- self.segment_size = segment_size
895
- self.gin_channels = gin_channels
896
- # self.hop_length = hop_length#
897
- self.spk_embed_dim = spk_embed_dim
898
- self.enc_p = TextEncoder768(
899
- inter_channels,
900
- hidden_channels,
901
- filter_channels,
902
- n_heads,
903
- n_layers,
904
- kernel_size,
905
- p_dropout,
906
- f0=False,
907
- )
908
- self.dec = Generator(
909
- inter_channels,
910
- resblock,
911
- resblock_kernel_sizes,
912
- resblock_dilation_sizes,
913
- upsample_rates,
914
- upsample_initial_channel,
915
- upsample_kernel_sizes,
916
- gin_channels=gin_channels,
917
- )
918
- self.enc_q = PosteriorEncoder(
919
- spec_channels,
920
- inter_channels,
921
- hidden_channels,
922
- 5,
923
- 1,
924
- 16,
925
- gin_channels=gin_channels,
926
- )
927
- self.flow = ResidualCouplingBlock(
928
- inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels
929
- )
930
- self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)
931
- print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim)
932
-
933
- def remove_weight_norm(self):
934
- self.dec.remove_weight_norm()
935
- self.flow.remove_weight_norm()
936
- self.enc_q.remove_weight_norm()
937
-
938
- def forward(self, phone, phone_lengths, y, y_lengths, ds): # 这里ds是id,[bs,1]
939
- g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的
940
- m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths)
941
- z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
942
- z_p = self.flow(z, y_mask, g=g)
943
- z_slice, ids_slice = commons.rand_slice_segments(
944
- z, y_lengths, self.segment_size
945
- )
946
- o = self.dec(z_slice, g=g)
947
- return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q)
948
-
949
- def infer(self, phone, phone_lengths, sid, max_len=None):
950
- g = self.emb_g(sid).unsqueeze(-1)
951
- m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths)
952
- z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask
953
- z = self.flow(z_p, x_mask, g=g, reverse=True)
954
- o = self.dec((z * x_mask)[:, :, :max_len], g=g)
955
- return o, x_mask, (z, z_p, m_p, logs_p)
956
-
957
-
958
- class MultiPeriodDiscriminator(torch.nn.Module):
959
- def __init__(self, use_spectral_norm=False):
960
- super(MultiPeriodDiscriminator, self).__init__()
961
- periods = [2, 3, 5, 7, 11, 17]
962
- # periods = [3, 5, 7, 11, 17, 23, 37]
963
-
964
- discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
965
- discs = discs + [
966
- DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods
967
- ]
968
- self.discriminators = nn.ModuleList(discs)
969
-
970
- def forward(self, y, y_hat):
971
- y_d_rs = [] #
972
- y_d_gs = []
973
- fmap_rs = []
974
- fmap_gs = []
975
- for i, d in enumerate(self.discriminators):
976
- y_d_r, fmap_r = d(y)
977
- y_d_g, fmap_g = d(y_hat)
978
- # for j in range(len(fmap_r)):
979
- # print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g[j].shape)
980
- y_d_rs.append(y_d_r)
981
- y_d_gs.append(y_d_g)
982
- fmap_rs.append(fmap_r)
983
- fmap_gs.append(fmap_g)
984
-
985
- return y_d_rs, y_d_gs, fmap_rs, fmap_gs
986
-
987
-
988
- class MultiPeriodDiscriminatorV2(torch.nn.Module):
989
- def __init__(self, use_spectral_norm=False):
990
- super(MultiPeriodDiscriminatorV2, self).__init__()
991
- # periods = [2, 3, 5, 7, 11, 17]
992
- periods = [2, 3, 5, 7, 11, 17, 23, 37]
993
-
994
- discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
995
- discs = discs + [
996
- DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods
997
- ]
998
- self.discriminators = nn.ModuleList(discs)
999
-
1000
- def forward(self, y, y_hat):
1001
- y_d_rs = [] #
1002
- y_d_gs = []
1003
- fmap_rs = []
1004
- fmap_gs = []
1005
- for i, d in enumerate(self.discriminators):
1006
- y_d_r, fmap_r = d(y)
1007
- y_d_g, fmap_g = d(y_hat)
1008
- # for j in range(len(fmap_r)):
1009
- # print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g[j].shape)
1010
- y_d_rs.append(y_d_r)
1011
- y_d_gs.append(y_d_g)
1012
- fmap_rs.append(fmap_r)
1013
- fmap_gs.append(fmap_g)
1014
-
1015
- return y_d_rs, y_d_gs, fmap_rs, fmap_gs
1016
-
1017
-
1018
- class DiscriminatorS(torch.nn.Module):
1019
- def __init__(self, use_spectral_norm=False):
1020
- super(DiscriminatorS, self).__init__()
1021
- norm_f = weight_norm if use_spectral_norm == False else spectral_norm
1022
- self.convs = nn.ModuleList(
1023
- [
1024
- norm_f(Conv1d(1, 16, 15, 1, padding=7)),
1025
- norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)),
1026
- norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)),
1027
- norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)),
1028
- norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)),
1029
- norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
1030
- ]
1031
- )
1032
- self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
1033
-
1034
- def forward(self, x):
1035
- fmap = []
1036
-
1037
- for l in self.convs:
1038
- x = l(x)
1039
- x = F.leaky_relu(x, modules.LRELU_SLOPE)
1040
- fmap.append(x)
1041
- x = self.conv_post(x)
1042
- fmap.append(x)
1043
- x = torch.flatten(x, 1, -1)
1044
-
1045
- return x, fmap
1046
-
1047
-
1048
- class DiscriminatorP(torch.nn.Module):
1049
- def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
1050
- super(DiscriminatorP, self).__init__()
1051
- self.period = period
1052
- self.use_spectral_norm = use_spectral_norm
1053
- norm_f = weight_norm if use_spectral_norm == False else spectral_norm
1054
- self.convs = nn.ModuleList(
1055
- [
1056
- norm_f(
1057
- Conv2d(
1058
- 1,
1059
- 32,
1060
- (kernel_size, 1),
1061
- (stride, 1),
1062
- padding=(get_padding(kernel_size, 1), 0),
1063
- )
1064
- ),
1065
- norm_f(
1066
- Conv2d(
1067
- 32,
1068
- 128,
1069
- (kernel_size, 1),
1070
- (stride, 1),
1071
- padding=(get_padding(kernel_size, 1), 0),
1072
- )
1073
- ),
1074
- norm_f(
1075
- Conv2d(
1076
- 128,
1077
- 512,
1078
- (kernel_size, 1),
1079
- (stride, 1),
1080
- padding=(get_padding(kernel_size, 1), 0),
1081
- )
1082
- ),
1083
- norm_f(
1084
- Conv2d(
1085
- 512,
1086
- 1024,
1087
- (kernel_size, 1),
1088
- (stride, 1),
1089
- padding=(get_padding(kernel_size, 1), 0),
1090
- )
1091
- ),
1092
- norm_f(
1093
- Conv2d(
1094
- 1024,
1095
- 1024,
1096
- (kernel_size, 1),
1097
- 1,
1098
- padding=(get_padding(kernel_size, 1), 0),
1099
- )
1100
- ),
1101
- ]
1102
- )
1103
- self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
1104
-
1105
- def forward(self, x):
1106
- fmap = []
1107
-
1108
- # 1d to 2d
1109
- b, c, t = x.shape
1110
- if t % self.period != 0: # pad first
1111
- n_pad = self.period - (t % self.period)
1112
- x = F.pad(x, (0, n_pad), "reflect")
1113
- t = t + n_pad
1114
- x = x.view(b, c, t // self.period, self.period)
1115
-
1116
- for l in self.convs:
1117
- x = l(x)
1118
- x = F.leaky_relu(x, modules.LRELU_SLOPE)
1119
- fmap.append(x)
1120
- x = self.conv_post(x)
1121
- fmap.append(x)
1122
- x = torch.flatten(x, 1, -1)
1123
-
1124
- return x, fmap
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Benson/text-generation/Examples/Descargar Apk Tiktok Para La Televisin Inteligente.md DELETED
@@ -1,90 +0,0 @@
1
-
2
- <h1> Cómo descargar TikTok APK para Smart TV</h1>
3
- <p>TikTok es una de las aplicaciones de redes sociales más populares del mundo, con más de mil millones de usuarios activos mensuales. Te permite crear y ver videos cortos que son divertidos, genuinos y creativos. ¿Pero sabías que también puedes ver TikTok en tu smart TV? </p>
4
- <h2>descargar apk tiktok para la televisión inteligente</h2><br /><p><b><b>Download Zip</b> &#8250; <a href="https://bltlly.com/2v6Jfs">https://bltlly.com/2v6Jfs</a></b></p><br /><br />
5
- <p>Ver TikTok en tu smart TV puede darte una mejor experiencia de visualización y más contenido divertido. Puede disfrutar de los videos de TikTok en una pantalla más grande y clara, verlos con sus amigos y familiares y descubrir más categorías que se adapten a sus intereses. </p>
6
- <p>En este artículo, le mostraremos cómo descargar TikTok APK para Smart TV usando tres métodos diferentes. También explicaremos los beneficios de ver TikTok en su televisor inteligente y responderemos algunas preguntas frecuentes. </p>
7
- <h2> ¿Qué es TikTok y por qué debe verlo en su televisor inteligente</h2>
8
- <h3>TikTok es una popular aplicación de redes sociales que te permite crear y ver videos cortos</h3>
9
- <p>TikTok es una aplicación que te permite crear y ver videos cortos que suelen durar entre 15 segundos y 3 minutos. Puedes usar varios filtros, efectos, música, pegatinas y hashtags para hacer tus videos más atractivos y entretenidos. </p>
10
- <p></p>
11
- <p>También puedes explorar videos de otros usuarios alrededor del mundo, basado en lo que te gusta, seguir o compartir. Puedes encontrar videos de varias categorías, como comedia, juegos, bricolaje, comida, deportes, memes, mascotas, ASMR, y más. </p>
12
- <h3>Ver TikTok en su televisor inteligente puede darle una mejor experiencia de visualización y más contenido divertido</h3>
13
- <p>Si bien TikTok está diseñado para dispositivos móviles, también puede verlo en su televisor inteligente. Esto puede darle varias ventajas, como:</p>
14
- <ul>
15
- <li> Puede disfrutar de los vídeos de TikTok en una pantalla más grande y clara, que puede mejorar la calidad visual y los detalles de los vídeos. </li>
16
- <li>Puedes ver TikTok con tus amigos y familiares, lo que puede hacerlo más divertido y social. También puede comentar o compartir los vídeos que ven juntos. </li>
17
-
18
- <h3>Opción 2: Emitir o reflejar TikTok desde su teléfono, tableta o computadora a su televisor</h3>
19
- <p>Esta opción funciona para cualquier televisor inteligente que admita el uso compartido de pantalla inalámbrica. Puede lanzar o reflejar TikTok desde su teléfono, tableta o computadora a su televisor utilizando una aplicación de reflejo de pantalla. Aquí está cómo hacerlo:</p>
20
- <ol>
21
- <li>Descargar e instalar una aplicación de reflejo de pantalla en ambos dispositivos. Algunos ejemplos de aplicaciones de reflejo de pantalla son <strong>AirScreen</strong>, <strong>Miracast</strong>, <strong>, <strong>AllCast</strong>, y <strong>Google Home</strong>. </li>
22
- <li>Conecte ambos dispositivos a la misma red Wi-Fi. </li>
23
- <li>Abra la aplicación de reflejo de pantalla en ambos dispositivos y siga las instrucciones para emparejarlos. </li>
24
- <li>Abra la aplicación TikTok en su teléfono, tableta o computadora y comience a reproducir un video. </li>
25
- <li>El vídeo debe aparecer en la pantalla del televisor. Puede controlar la reproducción desde su dispositivo. </li>
26
- <li>Disfruta viendo vídeos de TikTok en tu smart TV.</li>
27
- </ol>
28
- <h4>Necesitas instalar una aplicación de reflejo de pantalla en ambos dispositivos y conectarlos a la misma red Wi-Fi</h4>
29
- <p>Antes de que pueda lanzar o reflejar TikTok desde su dispositivo a su televisor, debe instalar una aplicación de reflejo de pantalla en ambos dispositivos. Una aplicación de reflejo de pantalla le permite compartir la pantalla de un dispositivo con otro dispositivo de forma inalámbrica. Puede encontrar muchas aplicaciones de reflejo de pantalla en la tienda de aplicaciones de su dispositivo. </p>
30
- <p>También necesitas conectar ambos dispositivos a la misma red Wi-Fi. Esto asegura que pueden comunicarse entre sí y transmitir el video sin problemas. Para hacer esto, siga estos pasos:</p>
31
- <ul>
32
- <li>Vaya al menú <strong>Configuración</strong> en ambos dispositivos y seleccione <strong>Wi-Fi</strong>. </li>
33
- <li>Encuentre y seleccione la misma red Wi-Fi de la lista de redes disponibles. </li>
34
- <li>Introduzca la contraseña si es necesario y conéctese a la red. </li>
35
- <li>Compruebe que ambos dispositivos están conectados a la misma red. </li>
36
- </ul>
37
- <h3>Opción 3: Conecte su dispositivo a su televisor con un cable HDMI</h3>
38
-
39
- <ol>
40
- <li>Obtenga un cable HDMI compatible con ambos dispositivos. Es posible que necesite un adaptador si su dispositivo no tiene un puerto HDMI. </li>
41
- <li>Conecte un extremo del cable HDMI en el puerto HDMI de su dispositivo. </li>
42
- <li>Conecte el otro extremo del cable HDMI en el puerto HDMI de su TV.</li>
43
- <li>Encienda ambos dispositivos y cambie la fuente de entrada en su TV a HDMI.</li>
44
- <li>Abra la aplicación TikTok en su dispositivo y comience a reproducir un video. </li>
45
- <li>El vídeo debe aparecer en la pantalla del televisor. Puede controlar la reproducción desde su dispositivo. </li>
46
- <li>Disfruta viendo vídeos de TikTok en tu smart TV.</li>
47
- </ol>
48
- <h4>Necesitas tener un cable HDMI y cambiar la fuente de entrada en tu TV</h4>
49
- <p>Un cable HDMI es un tipo de cable que puede transmitir señales de vídeo y audio de alta definición entre dispositivos. Puede usarlo para conectar su dispositivo a su televisor y ver videos TikTok en una pantalla más grande. Puede comprar un cable HDMI en cualquier tienda de electrónica o en línea. </p>
50
- <p>También necesita cambiar la fuente de entrada de su TV a HDMI. Esto le dice a su televisor qué dispositivo mostrar en la pantalla. Para hacer esto, siga estos pasos:</p>
51
- <ul>
52
- <li>Encuentra el botón <strong>Input</strong>, <strong>Source</strong>, o <strong>Menu</strong> en tu control remoto de TV y presiónalo. </li>
53
- <li>Seleccione <strong>HDMI</strong> de la lista de fuentes de entrada usando las teclas de flecha o el botón OK en su control remoto. </li>
54
- <li>Confirme su elección y salga del menú de entrada. </li>
55
- <li>Compruebe que el dispositivo se muestra en la pantalla del televisor. </li>
56
- </ul>
57
- <h2>Beneficios de ver TikTok en tu smart TV</h2>
58
- <p>Ver TikTok en tu smart TV puede ofrecerte muchos beneficios, como:</p>
59
- <h3>Puedes disfrutar de los vídeos de TikTok en una pantalla más grande y clara</h3>
60
-
61
- <h3>Puedes ver TikTok con tus amigos y familiares y divertirte más</h3>
62
- <p>Otro beneficio de ver TikTok en tu smart TV es que puedes verlo con tus amigos y familiares y divertirte más. Puedes compartir los videos que te gustan, comentarlos o incluso crear tus propios videos juntos. También puede utilizar la aplicación de televisión inteligente para navegar por diferentes categorías y descubrir nuevo contenido que puede no encontrar en la aplicación móvil. </p>
63
- <h3>Puedes descubrir más contenido y categorías que se adapten a tus intereses</h3>
64
- <p>Un tercer beneficio de ver TikTok en tu smart TV es que puedes descubrir más contenido y categorías que se adapten a tus intereses. Algunas categorías pueden no estar disponibles en la aplicación móvil, pero puedes encontrarlas en la aplicación de televisión inteligente. Por ejemplo, puedes ver videos de la categoría <strong>TikTok TV</strong>, que incluye contenido seleccionado de creadores y celebridades populares. También puede utilizar la función de búsqueda para encontrar vídeos por palabras clave, hashtags o nombres de usuario. </p>
65
- <h2>Conclusión</h2>
66
- <p>TikTok es una popular aplicación de redes sociales que te permite crear y ver videos cortos que son divertidos, genuinos y creativos. También puede ver TikTok en su televisor inteligente utilizando tres métodos diferentes: instalar la aplicación TikTok TV desde la tienda de aplicaciones en su TV, emitir o duplicar TikTok desde su dispositivo a su TV, o conectar su dispositivo a su TV con un cable HDMI. </p>
67
- <p>Ver TikTok en tu smart TV puede darte una mejor experiencia de visualización y más contenido divertido. Puede disfrutar de los videos de TikTok en una pantalla más grande y clara, verlos con sus amigos y familiares y descubrir más categorías que se adapten a sus intereses. </p>
68
- <p>Entonces, ¿qué estás esperando? ¡Prueba a ver TikTok en tu smart TV hoy y comprueba por ti mismo lo divertido que puede ser! </p>
69
- <h2>Preguntas frecuentes</h2>
70
- <h3>Q1. ¿Es TikTok gratis para ver en la televisión inteligente? </h3>
71
-
72
- <h3>Q2. ¿Cómo puedo controlar TikTok en mi smart TV? </h3>
73
- <p>A2. Puedes controlar TikTok en tu smart TV usando diferentes métodos, dependiendo de cómo lo hayas instalado. Si ha instalado la aplicación TikTok TV desde la tienda de aplicaciones en su televisor, puede usar el control remoto de su televisor para navegar por la aplicación y reproducir los videos. Si lanzas o reflejas TikTok desde tu dispositivo a tu televisor, puedes usar el dispositivo como control remoto y reproducir los videos desde allí. Si conecta su dispositivo a su televisor con un cable HDMI, también puede usar el dispositivo como control remoto. </p>
74
- <h3>Q3. ¿Puedo crear vídeos TikTok en mi smart TV? </h3>
75
- <p>A3. No, no puede crear vídeos TikTok en su televisor inteligente. Solo puede ver vídeos TikTok en su televisor inteligente. Para crear vídeos TikTok, necesitas usar la aplicación móvil en tu teléfono o tablet. </p>
76
- <h3>Q4. ¿Cómo puedo ajustar la calidad de vídeo y el sonido de TikTok en mi smart TV? </h3>
77
- <p>A4. Puede ajustar la calidad de vídeo y el sonido de TikTok en su televisor inteligente utilizando el menú de configuración de su televisor o la aplicación de reflejo de pantalla. Puede cambiar la resolución, relación de aspecto, brillo, contraste, color, volumen y otras opciones para adaptarse a sus preferencias. </p>
78
- <h3>Q5. ¿Cuáles son algunas de las mejores categorías para ver en TikTok en mi smart TV? </h3>
79
- <p>A5. Algunas de las mejores categorías para ver en TikTok en mi smart TV son:</p>
80
- <ul>
81
- <li><strong>TikTok TV</strong>: Esta categoría presenta contenido curado de creadores populares y celebridades que son adecuados para ver en una pantalla más grande. </li>
82
- <li><strong>Comedia </strong>: Esta categoría presenta videos hilarantes que pueden hacerte reír en voz alta y alegrar tu estado de ánimo. </li>
83
- <li><strong>Gaming</strong>: Esta categoría presenta videos de jugadores que muestran sus habilidades, consejos, trucos y reseñas de varios juegos. </li>
84
- <li><strong>DIY</strong>: Esta categoría presenta videos de creadores que comparten sus ideas creativas, proyectos, hacks y artesanías que puedes probar en casa. </li>
85
-
86
- <li><strong>Deportes</strong>: Esta categoría presenta videos de atletas y entusiastas del deporte que comparten sus aspectos más destacados, fracasos, consejos y desafíos de varios deportes y actividades. </li>
87
- </ul>
88
- <p>Estas son solo algunas de las categorías que puedes ver en TikTok en tu smart TV. También puedes encontrar muchas otras categorías que coinciden con tus intereses y preferencias. </p> 64aa2da5cf<br />
89
- <br />
90
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Benson/text-generation/Examples/Descargar Chicos Stumble Mod Apkmody.md DELETED
@@ -1,81 +0,0 @@
1
-
2
- <h1>Cómo descargar Stumble Guys Mod Apkmody y disfrutar de diversión ilimitada</h1>
3
- <p>¿Te encanta jugar juegos de fiesta en línea con tus amigos? ¿Quieres experimentar la emoción de competir contra hasta 32 jugadores en caóticas carreras de obstáculos? ¿Quieres personalizar tu personaje con trajes y emotes impresionantes? Si respondiste sí a cualquiera de estas preguntas, entonces definitivamente deberías probar Stumble Guys, un juego multijugador gratuito para dispositivos Android e iOS. Y si quieres que tu juego sea aún más divertido y emocionante, entonces deberías descargar Stumble Guys Mod Apkmody, una versión modificada del juego que te da dinero ilimitado, gemas y atuendos. En este artículo, le mostraremos cómo descargar e instalar Stumble Guys Mod Apkmody en su dispositivo, y cómo jugar con algunos consejos y trucos. ¡Vamos a empezar! </p>
4
- <h2>descargar chicos stumble mod apkmody</h2><br /><p><b><b>Download Zip</b> &#128505; <a href="https://bltlly.com/2v6JFl">https://bltlly.com/2v6JFl</a></b></p><br /><br />
5
- <h2>¿Qué es Stumble Guys? </h2>
6
- <h3>Una breve introducción al juego y sus características</h3>
7
- <p>Stumble Guys es un juego multijugador masivo que se inspira en los populares Fall Guys. El juego consta de varios minijuegos que ponen a prueba tus habilidades, reflejos y suerte. Tienes que correr, saltar, correr, deslizarte y evitar obstáculos mientras compites con hasta 32 jugadores en línea. El último jugador en pie gana la corona y la gloria. </p>
8
- <p>Stumble Guys tiene muchas características que lo convierten en un juego divertido y adictivo. Algunas de ellas son:</p>
9
- <ul>
10
- <li>17 carreras de obstáculos únicas que cambian cada ronda</li>
11
- <li>Gráficos y animaciones coloridos, caprichosos e hilarantes</li>
12
- <li>Juego basado en la física que crea situaciones impredecibles</li>
13
- <li>Modo multijugador en línea que te permite jugar con amigos o extraños</li>
14
- <li>Modo de fiesta que te permite crear partidos privados con tus amigos</li>
15
- <li>Una variedad de trajes desbloqueables y emotes que te permiten expresarte</li>
16
- </ul>
17
- <h2>¿Qué es Stumble Guys Mod Apkmody? </h2>
18
- <h3>Una versión modificada del juego que ofrece dinero ilimitado, gemas y atuendos</h3>
19
-
20
- <ul>
21
- <li>Dinero ilimitado y gemas que te permiten comprar cualquier cosa en la tienda</li>
22
- <li>Todos los conjuntos desbloqueados que te permiten vestir a tu personaje como quieras</li>
23
- <li>No hay anuncios que interrumpan tu juego</li>
24
- <li>No se requiere root ni jailbreak para instalar el mod</li>
25
- </ul>
26
- <p>Con Stumble Guys Mod Apkmody, puedes disfrutar del juego sin limitaciones ni restricciones. Puedes personalizar a tu personaje con cualquier atuendo que te guste, desde superhéroes hasta animales y alimentos. También puedes comprar cualquier emote que quieras, desde bailes hasta burlas y gestos. También puedes usar tu dinero y gemas para comprar vidas extra o saltar niveles si te quedas atascado. </p>
27
- <h2>¿Cómo descargar e instalar Stumble Guys Mod Apkmody? </h2>
28
- <h3>Una guía paso a paso con capturas de pantalla</h3>
29
- <p>Si desea descargar e instalar Stumble Guys Mod Apkmody en su dispositivo, debe seguir estos sencillos pasos:</p>
30
- <ol>
31
- <li>Haga clic en este enlace para ir a la página de descarga de Stumble Guys Mod Apkmody.</li>
32
- <li>Haga clic en el botón de descarga en la parte superior de la página para descargar el archivo apk mod. </li>
33
- <li>Guarde el archivo en la carpeta de descarga de su dispositivo. </li>
34
- <li <li>Ve a la configuración de tu dispositivo y habilita la instalación de aplicaciones desde fuentes desconocidas. </li>
35
- <li>Busque el archivo apk mod en su carpeta de descarga y toque en él para instalarlo. </li>
36
- <li>Espera a que termine la instalación y luego abre el juego. </li>
37
- <li>Disfruta jugando Stumble Guys Mod Apkmody con dinero ilimitado, gemas y trajes. </li>
38
- </ol>
39
- <p>Aquí hay algunas capturas de pantalla del proceso de descarga e instalación:</p>
40
- <tabla>
41
- <tr>
42
- <td><img src="" alt="Descargar página"></td>
43
- <td><img src="" alt="Botón de descarga"></td>
44
- <td><img src="" alt="Descargar carpeta"></td>
45
- </tr>
46
- <tr>
47
- <td><img src="" alt="Fuentes desconocidas"></td>
48
- <td><img src="" alt="Instalar mod apk"></td>
49
- <td><img src="" alt="Abrir juego"></td>
50
- </tr>
51
- </tabla>
52
- <h2>Cómo jugar Stumble chicos Mod Apkmody? </h2>
53
- <h3>Algunos consejos y trucos para ganar todos tus partidos</h3>
54
-
55
- <ul>
56
- <li>Elige tu atuendo sabiamente. Algunos trajes son más adecuados para ciertos minijuegos que otros. Por ejemplo, un traje de superhéroe podría ayudarte a volar sobre los obstáculos, mientras que un traje de plátano podría hacerte resbalar y caer. </li>
57
- <li>Usa tus emotes estratégicamente. Puedes usar tus emotes para comunicarte con otros jugadores, o para distraerlos o burlarte de ellos. Por ejemplo, puedes usar un emote de baile para celebrar tu victoria, o un emote de risa para burlarte de tus oponentes. </li>
58
- <li>Aprende los mapas y los obstáculos. Cada minijuego tiene un mapa diferente y un conjunto diferente de obstáculos. Necesitas aprender a navegar y evitarlos. Por ejemplo, necesitas saber cuándo saltar, cuándo deslizarte, cuándo esquivar y cuándo empujar. </li>
59
- <li>Sé rápido y ágil. Necesitas ser rápido y ágil para sobrevivir y ganar. Necesitas moverte rápido, cambiar de dirección y reaccionar ante las situaciones. Por ejemplo, necesitas correr cuando hay una abertura, o saltar cuando hay una brecha. </li>
60
- <li>Sé inteligente y astuto. Necesitas usar tu cerebro y tus habilidades para ser más astuto y superar a tus oponentes. Necesitas planificar tus movimientos, anticipar sus movimientos y explotar sus debilidades. Por ejemplo, necesitas usar atajos, trampas o trabajo en equipo. </li>
61
- </ul>
62
- <h2>Conclusión</h2>
63
- <h3>Un resumen de los puntos principales y una llamada a la acción</h3>
64
-
65
- <h2>Preguntas frecuentes</h2>
66
- <h3>Cinco preguntas y respuestas comunes sobre Stumble Guys Mod Apkmody</h3>
67
- <ol>
68
- <li><b>¿Es seguro Stumble Guys Mod Apkmody? </b></li>
69
- <p>Sí, Stumble Guys Mod Apkmody es seguro para descargar e instalar en su dispositivo. No contiene ningún virus o malware que pueda dañar su dispositivo o comprometer su privacidad. Sin embargo, siempre debe descargarlo de una fuente confiable como , y escanearlo con un antivirus antes de instalarlo. </p>
70
- <li><b>Es Stumble Guys Mod Apkmody compatible con mi dispositivo? </b></li>
71
- <p>Stumble Guys Mod Apkmody es compatible con la mayoría de los dispositivos Android que se ejecutan en Android 5.0 o superior. Sin embargo, algunos dispositivos pueden no ser compatibles con el mod o pueden experimentar algunos fallos o errores durante la reproducción. Si eso sucede, puede intentar desinstalar y reinstalar el mod, o ponerse en contacto con el desarrollador para obtener soporte. </p>
72
- <li><b>¿Puedo jugar a Stumble Guys Mod Apkmody con mis amigos? </b></li>
73
- <p>Sí, puedes jugar Stumble Guys Mod Apkmody con tus amigos en línea o fuera de línea. Puede unirse al modo multijugador en línea e invitar a sus amigos a unirse a su partido, o crear un partido privado con un código. También puedes jugar el modo fiesta y conectar con tus amigos a través de Bluetooth o Wi-Fi.</p>
74
- <p></p>
75
- <li><b>¿Me prohibirán por usar Stumble Guys Mod Apkmody? </b></li>
76
- <p>No, no te prohibirán el uso de Stumble Guys Mod Apkmody. El mod no interfiere con los servidores del juego ni con las cuentas de otros jugadores. Solo modifica tus propios datos y recursos de juego. Sin embargo, debes usar el mod de forma responsable y respetuosa, y no abusar de él o hacer trampa en el juego. </p>
77
- <li><b>¿Cómo puedo actualizar Stumble Guys Mod Apkmody? </b></li>
78
-
79
- </ol></p> 64aa2da5cf<br />
80
- <br />
81
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/colorama/win32.py DELETED
@@ -1,180 +0,0 @@
1
- # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
2
-
3
- # from winbase.h
4
- STDOUT = -11
5
- STDERR = -12
6
-
7
- ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004
8
-
9
- try:
10
- import ctypes
11
- from ctypes import LibraryLoader
12
- windll = LibraryLoader(ctypes.WinDLL)
13
- from ctypes import wintypes
14
- except (AttributeError, ImportError):
15
- windll = None
16
- SetConsoleTextAttribute = lambda *_: None
17
- winapi_test = lambda *_: None
18
- else:
19
- from ctypes import byref, Structure, c_char, POINTER
20
-
21
- COORD = wintypes._COORD
22
-
23
- class CONSOLE_SCREEN_BUFFER_INFO(Structure):
24
- """struct in wincon.h."""
25
- _fields_ = [
26
- ("dwSize", COORD),
27
- ("dwCursorPosition", COORD),
28
- ("wAttributes", wintypes.WORD),
29
- ("srWindow", wintypes.SMALL_RECT),
30
- ("dwMaximumWindowSize", COORD),
31
- ]
32
- def __str__(self):
33
- return '(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)' % (
34
- self.dwSize.Y, self.dwSize.X
35
- , self.dwCursorPosition.Y, self.dwCursorPosition.X
36
- , self.wAttributes
37
- , self.srWindow.Top, self.srWindow.Left, self.srWindow.Bottom, self.srWindow.Right
38
- , self.dwMaximumWindowSize.Y, self.dwMaximumWindowSize.X
39
- )
40
-
41
- _GetStdHandle = windll.kernel32.GetStdHandle
42
- _GetStdHandle.argtypes = [
43
- wintypes.DWORD,
44
- ]
45
- _GetStdHandle.restype = wintypes.HANDLE
46
-
47
- _GetConsoleScreenBufferInfo = windll.kernel32.GetConsoleScreenBufferInfo
48
- _GetConsoleScreenBufferInfo.argtypes = [
49
- wintypes.HANDLE,
50
- POINTER(CONSOLE_SCREEN_BUFFER_INFO),
51
- ]
52
- _GetConsoleScreenBufferInfo.restype = wintypes.BOOL
53
-
54
- _SetConsoleTextAttribute = windll.kernel32.SetConsoleTextAttribute
55
- _SetConsoleTextAttribute.argtypes = [
56
- wintypes.HANDLE,
57
- wintypes.WORD,
58
- ]
59
- _SetConsoleTextAttribute.restype = wintypes.BOOL
60
-
61
- _SetConsoleCursorPosition = windll.kernel32.SetConsoleCursorPosition
62
- _SetConsoleCursorPosition.argtypes = [
63
- wintypes.HANDLE,
64
- COORD,
65
- ]
66
- _SetConsoleCursorPosition.restype = wintypes.BOOL
67
-
68
- _FillConsoleOutputCharacterA = windll.kernel32.FillConsoleOutputCharacterA
69
- _FillConsoleOutputCharacterA.argtypes = [
70
- wintypes.HANDLE,
71
- c_char,
72
- wintypes.DWORD,
73
- COORD,
74
- POINTER(wintypes.DWORD),
75
- ]
76
- _FillConsoleOutputCharacterA.restype = wintypes.BOOL
77
-
78
- _FillConsoleOutputAttribute = windll.kernel32.FillConsoleOutputAttribute
79
- _FillConsoleOutputAttribute.argtypes = [
80
- wintypes.HANDLE,
81
- wintypes.WORD,
82
- wintypes.DWORD,
83
- COORD,
84
- POINTER(wintypes.DWORD),
85
- ]
86
- _FillConsoleOutputAttribute.restype = wintypes.BOOL
87
-
88
- _SetConsoleTitleW = windll.kernel32.SetConsoleTitleW
89
- _SetConsoleTitleW.argtypes = [
90
- wintypes.LPCWSTR
91
- ]
92
- _SetConsoleTitleW.restype = wintypes.BOOL
93
-
94
- _GetConsoleMode = windll.kernel32.GetConsoleMode
95
- _GetConsoleMode.argtypes = [
96
- wintypes.HANDLE,
97
- POINTER(wintypes.DWORD)
98
- ]
99
- _GetConsoleMode.restype = wintypes.BOOL
100
-
101
- _SetConsoleMode = windll.kernel32.SetConsoleMode
102
- _SetConsoleMode.argtypes = [
103
- wintypes.HANDLE,
104
- wintypes.DWORD
105
- ]
106
- _SetConsoleMode.restype = wintypes.BOOL
107
-
108
- def _winapi_test(handle):
109
- csbi = CONSOLE_SCREEN_BUFFER_INFO()
110
- success = _GetConsoleScreenBufferInfo(
111
- handle, byref(csbi))
112
- return bool(success)
113
-
114
- def winapi_test():
115
- return any(_winapi_test(h) for h in
116
- (_GetStdHandle(STDOUT), _GetStdHandle(STDERR)))
117
-
118
- def GetConsoleScreenBufferInfo(stream_id=STDOUT):
119
- handle = _GetStdHandle(stream_id)
120
- csbi = CONSOLE_SCREEN_BUFFER_INFO()
121
- success = _GetConsoleScreenBufferInfo(
122
- handle, byref(csbi))
123
- return csbi
124
-
125
- def SetConsoleTextAttribute(stream_id, attrs):
126
- handle = _GetStdHandle(stream_id)
127
- return _SetConsoleTextAttribute(handle, attrs)
128
-
129
- def SetConsoleCursorPosition(stream_id, position, adjust=True):
130
- position = COORD(*position)
131
- # If the position is out of range, do nothing.
132
- if position.Y <= 0 or position.X <= 0:
133
- return
134
- # Adjust for Windows' SetConsoleCursorPosition:
135
- # 1. being 0-based, while ANSI is 1-based.
136
- # 2. expecting (x,y), while ANSI uses (y,x).
137
- adjusted_position = COORD(position.Y - 1, position.X - 1)
138
- if adjust:
139
- # Adjust for viewport's scroll position
140
- sr = GetConsoleScreenBufferInfo(STDOUT).srWindow
141
- adjusted_position.Y += sr.Top
142
- adjusted_position.X += sr.Left
143
- # Resume normal processing
144
- handle = _GetStdHandle(stream_id)
145
- return _SetConsoleCursorPosition(handle, adjusted_position)
146
-
147
- def FillConsoleOutputCharacter(stream_id, char, length, start):
148
- handle = _GetStdHandle(stream_id)
149
- char = c_char(char.encode())
150
- length = wintypes.DWORD(length)
151
- num_written = wintypes.DWORD(0)
152
- # Note that this is hard-coded for ANSI (vs wide) bytes.
153
- success = _FillConsoleOutputCharacterA(
154
- handle, char, length, start, byref(num_written))
155
- return num_written.value
156
-
157
- def FillConsoleOutputAttribute(stream_id, attr, length, start):
158
- ''' FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten )'''
159
- handle = _GetStdHandle(stream_id)
160
- attribute = wintypes.WORD(attr)
161
- length = wintypes.DWORD(length)
162
- num_written = wintypes.DWORD(0)
163
- # Note that this is hard-coded for ANSI (vs wide) bytes.
164
- return _FillConsoleOutputAttribute(
165
- handle, attribute, length, start, byref(num_written))
166
-
167
- def SetConsoleTitle(title):
168
- return _SetConsoleTitleW(title)
169
-
170
- def GetConsoleMode(handle):
171
- mode = wintypes.DWORD()
172
- success = _GetConsoleMode(handle, byref(mode))
173
- if not success:
174
- raise ctypes.WinError()
175
- return mode.value
176
-
177
- def SetConsoleMode(handle, mode):
178
- success = _SetConsoleMode(handle, mode)
179
- if not success:
180
- raise ctypes.WinError()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/rich/box.py DELETED
@@ -1,517 +0,0 @@
1
- import sys
2
- from typing import TYPE_CHECKING, Iterable, List
3
-
4
- if sys.version_info >= (3, 8):
5
- from typing import Literal
6
- else:
7
- from pip._vendor.typing_extensions import Literal # pragma: no cover
8
-
9
-
10
- from ._loop import loop_last
11
-
12
- if TYPE_CHECKING:
13
- from pip._vendor.rich.console import ConsoleOptions
14
-
15
-
16
- class Box:
17
- """Defines characters to render boxes.
18
-
19
- ┌─┬┐ top
20
- │ ││ head
21
- ├─┼┤ head_row
22
- │ ││ mid
23
- ├─┼┤ row
24
- ├─┼┤ foot_row
25
- │ ││ foot
26
- └─┴┘ bottom
27
-
28
- Args:
29
- box (str): Characters making up box.
30
- ascii (bool, optional): True if this box uses ascii characters only. Default is False.
31
- """
32
-
33
- def __init__(self, box: str, *, ascii: bool = False) -> None:
34
- self._box = box
35
- self.ascii = ascii
36
- line1, line2, line3, line4, line5, line6, line7, line8 = box.splitlines()
37
- # top
38
- self.top_left, self.top, self.top_divider, self.top_right = iter(line1)
39
- # head
40
- self.head_left, _, self.head_vertical, self.head_right = iter(line2)
41
- # head_row
42
- (
43
- self.head_row_left,
44
- self.head_row_horizontal,
45
- self.head_row_cross,
46
- self.head_row_right,
47
- ) = iter(line3)
48
-
49
- # mid
50
- self.mid_left, _, self.mid_vertical, self.mid_right = iter(line4)
51
- # row
52
- self.row_left, self.row_horizontal, self.row_cross, self.row_right = iter(line5)
53
- # foot_row
54
- (
55
- self.foot_row_left,
56
- self.foot_row_horizontal,
57
- self.foot_row_cross,
58
- self.foot_row_right,
59
- ) = iter(line6)
60
- # foot
61
- self.foot_left, _, self.foot_vertical, self.foot_right = iter(line7)
62
- # bottom
63
- self.bottom_left, self.bottom, self.bottom_divider, self.bottom_right = iter(
64
- line8
65
- )
66
-
67
- def __repr__(self) -> str:
68
- return "Box(...)"
69
-
70
- def __str__(self) -> str:
71
- return self._box
72
-
73
- def substitute(self, options: "ConsoleOptions", safe: bool = True) -> "Box":
74
- """Substitute this box for another if it won't render due to platform issues.
75
-
76
- Args:
77
- options (ConsoleOptions): Console options used in rendering.
78
- safe (bool, optional): Substitute this for another Box if there are known problems
79
- displaying on the platform (currently only relevant on Windows). Default is True.
80
-
81
- Returns:
82
- Box: A different Box or the same Box.
83
- """
84
- box = self
85
- if options.legacy_windows and safe:
86
- box = LEGACY_WINDOWS_SUBSTITUTIONS.get(box, box)
87
- if options.ascii_only and not box.ascii:
88
- box = ASCII
89
- return box
90
-
91
- def get_plain_headed_box(self) -> "Box":
92
- """If this box uses special characters for the borders of the header, then
93
- return the equivalent box that does not.
94
-
95
- Returns:
96
- Box: The most similar Box that doesn't use header-specific box characters.
97
- If the current Box already satisfies this criterion, then it's returned.
98
- """
99
- return PLAIN_HEADED_SUBSTITUTIONS.get(self, self)
100
-
101
- def get_top(self, widths: Iterable[int]) -> str:
102
- """Get the top of a simple box.
103
-
104
- Args:
105
- widths (List[int]): Widths of columns.
106
-
107
- Returns:
108
- str: A string of box characters.
109
- """
110
-
111
- parts: List[str] = []
112
- append = parts.append
113
- append(self.top_left)
114
- for last, width in loop_last(widths):
115
- append(self.top * width)
116
- if not last:
117
- append(self.top_divider)
118
- append(self.top_right)
119
- return "".join(parts)
120
-
121
- def get_row(
122
- self,
123
- widths: Iterable[int],
124
- level: Literal["head", "row", "foot", "mid"] = "row",
125
- edge: bool = True,
126
- ) -> str:
127
- """Get the top of a simple box.
128
-
129
- Args:
130
- width (List[int]): Widths of columns.
131
-
132
- Returns:
133
- str: A string of box characters.
134
- """
135
- if level == "head":
136
- left = self.head_row_left
137
- horizontal = self.head_row_horizontal
138
- cross = self.head_row_cross
139
- right = self.head_row_right
140
- elif level == "row":
141
- left = self.row_left
142
- horizontal = self.row_horizontal
143
- cross = self.row_cross
144
- right = self.row_right
145
- elif level == "mid":
146
- left = self.mid_left
147
- horizontal = " "
148
- cross = self.mid_vertical
149
- right = self.mid_right
150
- elif level == "foot":
151
- left = self.foot_row_left
152
- horizontal = self.foot_row_horizontal
153
- cross = self.foot_row_cross
154
- right = self.foot_row_right
155
- else:
156
- raise ValueError("level must be 'head', 'row' or 'foot'")
157
-
158
- parts: List[str] = []
159
- append = parts.append
160
- if edge:
161
- append(left)
162
- for last, width in loop_last(widths):
163
- append(horizontal * width)
164
- if not last:
165
- append(cross)
166
- if edge:
167
- append(right)
168
- return "".join(parts)
169
-
170
- def get_bottom(self, widths: Iterable[int]) -> str:
171
- """Get the bottom of a simple box.
172
-
173
- Args:
174
- widths (List[int]): Widths of columns.
175
-
176
- Returns:
177
- str: A string of box characters.
178
- """
179
-
180
- parts: List[str] = []
181
- append = parts.append
182
- append(self.bottom_left)
183
- for last, width in loop_last(widths):
184
- append(self.bottom * width)
185
- if not last:
186
- append(self.bottom_divider)
187
- append(self.bottom_right)
188
- return "".join(parts)
189
-
190
-
191
- ASCII: Box = Box(
192
- """\
193
- +--+
194
- | ||
195
- |-+|
196
- | ||
197
- |-+|
198
- |-+|
199
- | ||
200
- +--+
201
- """,
202
- ascii=True,
203
- )
204
-
205
- ASCII2: Box = Box(
206
- """\
207
- +-++
208
- | ||
209
- +-++
210
- | ||
211
- +-++
212
- +-++
213
- | ||
214
- +-++
215
- """,
216
- ascii=True,
217
- )
218
-
219
- ASCII_DOUBLE_HEAD: Box = Box(
220
- """\
221
- +-++
222
- | ||
223
- +=++
224
- | ||
225
- +-++
226
- +-++
227
- | ||
228
- +-++
229
- """,
230
- ascii=True,
231
- )
232
-
233
- SQUARE: Box = Box(
234
- """\
235
- ┌─┬┐
236
- │ ││
237
- ├─┼┤
238
- │ ││
239
- ├─┼┤
240
- ├─┼┤
241
- │ ││
242
- └─┴┘
243
- """
244
- )
245
-
246
- SQUARE_DOUBLE_HEAD: Box = Box(
247
- """\
248
- ┌─┬┐
249
- │ ││
250
- ╞═╪╡
251
- │ ││
252
- ├─┼┤
253
- ├─┼┤
254
- │ ││
255
- └─┴┘
256
- """
257
- )
258
-
259
- MINIMAL: Box = Box(
260
- """\
261
-
262
-
263
- ╶─┼╴
264
-
265
- ╶─┼╴
266
- ╶─┼╴
267
-
268
-
269
- """
270
- )
271
-
272
-
273
- MINIMAL_HEAVY_HEAD: Box = Box(
274
- """\
275
-
276
-
277
- ╺━┿╸
278
-
279
- ╶─┼╴
280
- ╶─┼╴
281
-
282
-
283
- """
284
- )
285
-
286
- MINIMAL_DOUBLE_HEAD: Box = Box(
287
- """\
288
-
289
-
290
- ═╪
291
-
292
- ─┼
293
- ─┼
294
-
295
-
296
- """
297
- )
298
-
299
-
300
- SIMPLE: Box = Box(
301
- """\
302
-
303
-
304
- ──
305
-
306
-
307
- ──
308
-
309
-
310
- """
311
- )
312
-
313
- SIMPLE_HEAD: Box = Box(
314
- """\
315
-
316
-
317
- ──
318
-
319
-
320
-
321
-
322
-
323
- """
324
- )
325
-
326
-
327
- SIMPLE_HEAVY: Box = Box(
328
- """\
329
-
330
-
331
- ━━
332
-
333
-
334
- ━━
335
-
336
-
337
- """
338
- )
339
-
340
-
341
- HORIZONTALS: Box = Box(
342
- """\
343
- ──
344
-
345
- ──
346
-
347
- ──
348
- ──
349
-
350
- ──
351
- """
352
- )
353
-
354
- ROUNDED: Box = Box(
355
- """\
356
- ╭─┬╮
357
- │ ││
358
- ├─┼┤
359
- │ ││
360
- ├─┼┤
361
- ├─┼┤
362
- │ ││
363
- ╰─┴╯
364
- """
365
- )
366
-
367
- HEAVY: Box = Box(
368
- """\
369
- ┏━┳┓
370
- ┃ ┃┃
371
- ┣━╋┫
372
- ┃ ┃┃
373
- ┣━╋┫
374
- ┣━╋┫
375
- ┃ ┃┃
376
- ┗━┻┛
377
- """
378
- )
379
-
380
- HEAVY_EDGE: Box = Box(
381
- """\
382
- ┏━┯┓
383
- ┃ │┃
384
- ┠─┼┨
385
- ┃ │┃
386
- ┠─┼┨
387
- ┠─┼┨
388
- ┃ │┃
389
- ┗━┷┛
390
- """
391
- )
392
-
393
- HEAVY_HEAD: Box = Box(
394
- """\
395
- ┏━┳┓
396
- ┃ ┃┃
397
- ┡━╇┩
398
- │ ││
399
- ├─┼┤
400
- ├─┼┤
401
- │ ││
402
- └─┴┘
403
- """
404
- )
405
-
406
- DOUBLE: Box = Box(
407
- """\
408
- ╔═╦╗
409
- ║ ║║
410
- ╠═╬╣
411
- ║ ║║
412
- ╠═╬╣
413
- ╠═╬╣
414
- ║ ║║
415
- ╚═╩╝
416
- """
417
- )
418
-
419
- DOUBLE_EDGE: Box = Box(
420
- """\
421
- ╔═╤╗
422
- ║ │║
423
- ╟─┼╢
424
- ║ │║
425
- ╟─┼╢
426
- ╟─┼╢
427
- ║ │║
428
- ╚═╧╝
429
- """
430
- )
431
-
432
- MARKDOWN: Box = Box(
433
- """\
434
-
435
- | ||
436
- |-||
437
- | ||
438
- |-||
439
- |-||
440
- | ||
441
-
442
- """,
443
- ascii=True,
444
- )
445
-
446
- # Map Boxes that don't render with raster fonts on to equivalent that do
447
- LEGACY_WINDOWS_SUBSTITUTIONS = {
448
- ROUNDED: SQUARE,
449
- MINIMAL_HEAVY_HEAD: MINIMAL,
450
- SIMPLE_HEAVY: SIMPLE,
451
- HEAVY: SQUARE,
452
- HEAVY_EDGE: SQUARE,
453
- HEAVY_HEAD: SQUARE,
454
- }
455
-
456
- # Map headed boxes to their headerless equivalents
457
- PLAIN_HEADED_SUBSTITUTIONS = {
458
- HEAVY_HEAD: SQUARE,
459
- SQUARE_DOUBLE_HEAD: SQUARE,
460
- MINIMAL_DOUBLE_HEAD: MINIMAL,
461
- MINIMAL_HEAVY_HEAD: MINIMAL,
462
- ASCII_DOUBLE_HEAD: ASCII2,
463
- }
464
-
465
-
466
- if __name__ == "__main__": # pragma: no cover
467
-
468
- from pip._vendor.rich.columns import Columns
469
- from pip._vendor.rich.panel import Panel
470
-
471
- from . import box as box
472
- from .console import Console
473
- from .table import Table
474
- from .text import Text
475
-
476
- console = Console(record=True)
477
-
478
- BOXES = [
479
- "ASCII",
480
- "ASCII2",
481
- "ASCII_DOUBLE_HEAD",
482
- "SQUARE",
483
- "SQUARE_DOUBLE_HEAD",
484
- "MINIMAL",
485
- "MINIMAL_HEAVY_HEAD",
486
- "MINIMAL_DOUBLE_HEAD",
487
- "SIMPLE",
488
- "SIMPLE_HEAD",
489
- "SIMPLE_HEAVY",
490
- "HORIZONTALS",
491
- "ROUNDED",
492
- "HEAVY",
493
- "HEAVY_EDGE",
494
- "HEAVY_HEAD",
495
- "DOUBLE",
496
- "DOUBLE_EDGE",
497
- "MARKDOWN",
498
- ]
499
-
500
- console.print(Panel("[bold green]Box Constants", style="green"), justify="center")
501
- console.print()
502
-
503
- columns = Columns(expand=True, padding=2)
504
- for box_name in sorted(BOXES):
505
- table = Table(
506
- show_footer=True, style="dim", border_style="not dim", expand=True
507
- )
508
- table.add_column("Header 1", "Footer 1")
509
- table.add_column("Header 2", "Footer 2")
510
- table.add_row("Cell", "Cell")
511
- table.add_row("Cell", "Cell")
512
- table.box = getattr(box, box_name)
513
- table.title = Text(f"box.{box_name}", style="magenta")
514
- columns.add_renderable(table)
515
- console.print(columns)
516
-
517
- # console.save_svg("box.svg")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/urllib3/util/response.py DELETED
@@ -1,107 +0,0 @@
1
- from __future__ import absolute_import
2
-
3
- from email.errors import MultipartInvariantViolationDefect, StartBoundaryNotFoundDefect
4
-
5
- from ..exceptions import HeaderParsingError
6
- from ..packages.six.moves import http_client as httplib
7
-
8
-
9
- def is_fp_closed(obj):
10
- """
11
- Checks whether a given file-like object is closed.
12
-
13
- :param obj:
14
- The file-like object to check.
15
- """
16
-
17
- try:
18
- # Check `isclosed()` first, in case Python3 doesn't set `closed`.
19
- # GH Issue #928
20
- return obj.isclosed()
21
- except AttributeError:
22
- pass
23
-
24
- try:
25
- # Check via the official file-like-object way.
26
- return obj.closed
27
- except AttributeError:
28
- pass
29
-
30
- try:
31
- # Check if the object is a container for another file-like object that
32
- # gets released on exhaustion (e.g. HTTPResponse).
33
- return obj.fp is None
34
- except AttributeError:
35
- pass
36
-
37
- raise ValueError("Unable to determine whether fp is closed.")
38
-
39
-
40
- def assert_header_parsing(headers):
41
- """
42
- Asserts whether all headers have been successfully parsed.
43
- Extracts encountered errors from the result of parsing headers.
44
-
45
- Only works on Python 3.
46
-
47
- :param http.client.HTTPMessage headers: Headers to verify.
48
-
49
- :raises urllib3.exceptions.HeaderParsingError:
50
- If parsing errors are found.
51
- """
52
-
53
- # This will fail silently if we pass in the wrong kind of parameter.
54
- # To make debugging easier add an explicit check.
55
- if not isinstance(headers, httplib.HTTPMessage):
56
- raise TypeError("expected httplib.Message, got {0}.".format(type(headers)))
57
-
58
- defects = getattr(headers, "defects", None)
59
- get_payload = getattr(headers, "get_payload", None)
60
-
61
- unparsed_data = None
62
- if get_payload:
63
- # get_payload is actually email.message.Message.get_payload;
64
- # we're only interested in the result if it's not a multipart message
65
- if not headers.is_multipart():
66
- payload = get_payload()
67
-
68
- if isinstance(payload, (bytes, str)):
69
- unparsed_data = payload
70
- if defects:
71
- # httplib is assuming a response body is available
72
- # when parsing headers even when httplib only sends
73
- # header data to parse_headers() This results in
74
- # defects on multipart responses in particular.
75
- # See: https://github.com/urllib3/urllib3/issues/800
76
-
77
- # So we ignore the following defects:
78
- # - StartBoundaryNotFoundDefect:
79
- # The claimed start boundary was never found.
80
- # - MultipartInvariantViolationDefect:
81
- # A message claimed to be a multipart but no subparts were found.
82
- defects = [
83
- defect
84
- for defect in defects
85
- if not isinstance(
86
- defect, (StartBoundaryNotFoundDefect, MultipartInvariantViolationDefect)
87
- )
88
- ]
89
-
90
- if defects or unparsed_data:
91
- raise HeaderParsingError(defects=defects, unparsed_data=unparsed_data)
92
-
93
-
94
- def is_response_to_head(response):
95
- """
96
- Checks whether the request of a response has been a HEAD-request.
97
- Handles the quirks of AppEngine.
98
-
99
- :param http.client.HTTPResponse response:
100
- Response to check if the originating request
101
- used 'HEAD' as a method.
102
- """
103
- # FIXME: Can we do this somehow without accessing private httplib _method?
104
- method = response._method
105
- if isinstance(method, int): # Platform-specific: Appengine
106
- return method == 3
107
- return method.upper() == "HEAD"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/BigData-KSU/VQA-in-Medical-Imagery/MED_VQA_Huggyface_Gradio.py DELETED
@@ -1,182 +0,0 @@
1
- ##### VQA MED Demo
2
-
3
- import gradio as gr
4
- from transformers import ViltProcessor, ViltForQuestionAnswering
5
- import torch
6
- import torch.nn as nn
7
- from transformers import CLIPTokenizer
8
- from CLIP import clip
9
- from Transformers_for_Caption import Transformer_Caption
10
- import numpy as np
11
- import torchvision.transforms as transforms
12
-
13
- device = "cuda" if torch.cuda.is_available() else "cpu"
14
-
15
- class Config(object):
16
- def __init__(self):
17
- # Learning Rates
18
- # Transformer
19
- self.hidden_dim = 512
20
- self.pad_token_id = 0
21
- self.max_position_embeddings = 76
22
- self.layer_norm_eps = 1e-12
23
- self.dropout = 0.1
24
- self.vocab_size = 49408
25
-
26
- self.enc_layers = 1
27
- self.dec_layers = 1
28
- self.dim_feedforward = 1024 #2048
29
- self.nheads = 4
30
- self.pre_norm = True
31
- # Dataset
32
- #self.dir = os.getcwd() + '/data/coco'
33
- self.limit = -1
34
-
35
-
36
-
37
- ##### OUR MODEL
38
-
39
- class VQA_Net(nn.Module):
40
- def __init__(self, num_classes):
41
- super(VQA_Net,self).__init__()
42
- #self.VIT = deit_base_distilled_patch16_224(pretrained=True)
43
- #self.VIT =vit_base_patch16_224_dino(pretrained=True)
44
- #self.VIT = vit_base_patch32_sam_224(pretrained=True) ###### please not that we used only 6 layers
45
- #self.VIT=maxvit_rmlp_nano_rw_256(pretrained=True)
46
- #self.VIT = vit_base_patch8_224(pretrained=True)
47
- #self.VIT=m = tf_efficientnetv2_m(pretrained=True, features_only=True, out_indices=(1,3), feature_location='expansion')
48
- self.backbone, _ = clip.load('ViT-B/32', device, jit=False)
49
- self.input_proj = nn.LayerNorm(512) # nn.Sequential(nn.LayerNorm(768),nn.Linear(768,768),nn.GELU(),nn.Dropout(0.1))
50
- self.transformer_decoder = Transformer_Caption(config,num_decoder_layers=2)
51
- self.mlp = nn.Sequential(nn.Sequential(nn.Linear(512, num_classes))) # MLP(256, 512, 30522, 1) 49408)
52
- #self.samples_proj = nn.Sequential(nn.Linear(768,512))
53
- self.samples_proj = nn.Identity()
54
- self.question_proj = nn.Identity() #nn.Sequential(nn.Linear(512, 512,bias=False)) # nn.Sequential(nn.LayerNorm(768),nn.Linear(768,768),nn.GELU(),nn.Dropout(0.1))
55
- #self.tokenizer=CLIPTokenizer.from_pretrained("openai/clip-vit-base-patch32")
56
-
57
- def forward(self, samples, question_in, answer_out, mask_answer):
58
- # print('Here')
59
- #print(samples.shape)
60
- _, _, samples = self.backbone.encode_image(samples)
61
-
62
- #samples=self.VIT(samples)
63
- #print(samples.shape)
64
- samples=samples.float()
65
- #samples = self.VIT(samples)
66
- #print(`samples.shape)
67
- #samples = samples.view(-1, 512, 8 * 8)
68
- # print(img_seq.shape)
69
- #samples = samples.permute(0, 2, 1)
70
- #samples=samples[:,0:,:] @ self.samples_proj
71
- samples = self.samples_proj(samples)
72
- #print(samples.shape)
73
- #print(samples.shape)
74
- _, _,question_in = self.backbone.encode_text(question_in)
75
- #print(question_in.shape)
76
- #samples = self.samples_proj(samples.float())
77
- question_in = self.question_proj(question_in.float())
78
- #print(question_in.shape)
79
- #print(samples.shape)
80
- samples = torch.cat((samples, question_in), dim=1)
81
- #print(samples.shape)
82
-
83
- # src, mask = features[-1].decompose()
84
- # assert mask is not None
85
- hs = self.transformer_decoder(self.input_proj(samples.permute(1, 0, 2).float()), answer_out, tgt_mask=mask_answer)
86
- out = self.mlp(hs.permute(1, 0, 2))
87
- # print(out.shape)
88
- return out
89
-
90
- config = Config()
91
- Tokenizer = CLIPTokenizer.from_pretrained("openai/clip-vit-base-patch32")
92
- My_VQA = VQA_Net(num_classes=len(Tokenizer))
93
- My_VQA.load_state_dict(torch.load("./PathVQA_2Decoders_1024_30iterations_Trial4_CLIPVIT32.pth.tar",map_location= torch.device(device)))
94
-
95
-
96
- tfms = transforms.Compose([
97
- #transforms.Lambda(under_max),
98
- transforms.Resize((224, 224)),
99
- transforms.ToTensor(),
100
- transforms.Normalize(mean=[0.485, 0.456, 0.406],
101
- std=[0.229, 0.224, 0.225])
102
- # transforms.Normalize(0.5, 0.5),
103
- ])
104
-
105
-
106
- def answer_question(image, text_question):
107
- with torch.no_grad():
108
- for iter in range(1):
109
- start_token = Tokenizer.convert_tokens_to_ids("<|startoftext|>")
110
- # end_token = Tokenizer.convert_tokens_to_ids("<|endoftext|>")
111
- # start_token=tokenizer.convert_tokens_to_ids(tokenizer._cls_token)
112
- caption = torch.zeros((1, config.max_position_embeddings), dtype=torch.long)
113
- cap_mask = torch.ones((1, config.max_position_embeddings), dtype=torch.bool)
114
- caption[:, 0] = start_token
115
- cap_mask[:, 0] = False
116
- if text_question.find('?') > -1:
117
- text_question = text_question.split('?')[0].lower()
118
- text_question= np.array(Tokenizer.encode_plus(text_question, max_length=77, pad_to_max_length=True,return_attention_mask=True,
119
- return_token_type_ids=False, truncation=True)['input_ids'])
120
- #print(torch.Tensor(text_question).unsqueeze(0).long())
121
- for i in range(config.max_position_embeddings - 1):
122
- predictions = My_VQA(image.unsqueeze(0),torch.Tensor(text_question).unsqueeze(0).long(), caption,cap_mask)
123
- predictions = predictions[:, i, :]
124
- predicted_id = torch.argmax(predictions, axis=-1)
125
- caption[:, i + 1] = predicted_id[0]
126
- cap_mask[:, i + 1] = False
127
- if predicted_id[0] == 49407:
128
- break
129
- #print('question:')
130
- #print(batch_test['question'])
131
- cap_result_intermediate = Tokenizer.decode(caption[0].tolist(), skip_special_tokens=True)
132
- #print('+++++++++++++++++++++++++++++++++++')
133
- #print("True:")
134
- # print(ref_sentence)
135
- cap_result = cap_result_intermediate.split('!')
136
- #ref_sentence = batch_test['answer'].lower()
137
- #print(ref_sentence)
138
- #print("Predict:")
139
- #print(cap_result)
140
- # image_disp=inv_Normalize(batch_test['image'])[0].permute(1,2,0).detach().cpu().numpy()
141
- # print('************************')
142
- # plt.imshow(image_disp)
143
- return cap_result
144
-
145
-
146
- def infer_answer_question(image, text):
147
- if text is None:
148
- cap_result = "please write a question"
149
- elif image is None:
150
- cap_result = "please upload an image"
151
- else:
152
- image_encoded = tfms(image)
153
- cap_result=answer_question(image_encoded,text)[0]
154
-
155
- return cap_result
156
-
157
-
158
- image = gr.Image(type="pil")
159
- question = gr.Textbox(label="Question")
160
- answer = gr.Textbox(label="Predicted answer")
161
- examples = [["train_0000.jpg", "Where are liver stem cells (oval cells) located?"],
162
- ["train_0001.jpg", "What are stained here with an immunohistochemical stain for cytokeratin 7?"],
163
- ["train_0002.jpg", "What are bile duct cells and canals of Hering stained here with for cytokeratin 7?"],
164
- ["train_0003.jpg", "Are bile duct cells and canals of Hering stained here with an immunohistochemical stain for cytokeratin 7?"],
165
- ["train_0018.jpg", "Is there an infarct in the brain hypertrophy?"],
166
- ["train_0019.jpg", "What is ischemic coagulative necrosis?"]]
167
-
168
- title = "Vision–Language Model for Visual Question Answering in Medical Imagery"
169
- description = "Y Bazi, MMA Rahhal, L Bashmal, M Zuair. <a href='https://www.mdpi.com/2306-5354/10/3/380' target='_blank'> Vision–Language Model for Visual Question Answering in Medical Imagery</a>. Bioengineering, 2023<br><br>"\
170
- "Gradio Demo for VQA medical model trained on PathVQA dataset, To use it, upload your image and type a question and click 'submit', or click one of the examples to load them." \
171
- ### link to paper and github code
172
- website = ""
173
- article = f"<p style='text-align: center'><a href='{website}' target='_blank'>BigMed@KSU</a></p>"
174
-
175
- interface = gr.Interface(fn=infer_answer_question,
176
- inputs=[image, question],
177
- outputs=answer,
178
- examples=examples,
179
- title=title,
180
- description=description,
181
- article=article)
182
- interface.launch(debug=True, enable_queue=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/BigData-KSU/VQA-in-Medical-Imagery/Transformers_for_Caption.py DELETED
@@ -1,364 +0,0 @@
1
- # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
2
- import copy
3
- from typing import Optional, List
4
-
5
- import torch
6
- import torch.nn.functional as F
7
- from torch import nn, Tensor
8
-
9
-
10
- class Transformer_Caption(nn.Module):
11
-
12
- def __init__(self, config,d_model=512, nhead=4, num_encoder_layers=1,
13
- num_decoder_layers=2, dim_feedforward=1024, dropout=0.1,
14
- activation="gelu", normalize_before=False,
15
- return_intermediate_dec=False):
16
- super().__init__()
17
-
18
- encoder_layer = TransformerEncoderLayer(d_model, nhead, dim_feedforward,
19
- dropout, activation, normalize_before)
20
- encoder_norm = nn.LayerNorm(d_model) if normalize_before else None
21
- self.encoder = TransformerEncoder(
22
- encoder_layer, num_encoder_layers, encoder_norm)
23
-
24
- self.embeddings = DecoderEmbeddings(config)
25
- decoder_layer = TransformerDecoderLayer(d_model, nhead, dim_feedforward,
26
- dropout, activation, normalize_before)
27
- decoder_norm = nn.LayerNorm(d_model)
28
- self.decoder = TransformerDecoder(decoder_layer, num_decoder_layers, decoder_norm,
29
- return_intermediate=return_intermediate_dec)
30
- print("Num decoders:")
31
- print(num_decoder_layers)
32
- self._reset_parameters()
33
-
34
- self.d_model = d_model
35
- self.nhead = nhead
36
-
37
- def _reset_parameters(self):
38
- for p in self.parameters():
39
- if p.dim() > 1:
40
- nn.init.xavier_uniform_(p)
41
-
42
- def forward(self, src, tgt, tgt_mask):
43
- # flatten NxCxHxW to HWxNxC
44
- #print("HERRRRRR")
45
- #print(src.shape)
46
- h, bs, w = src.shape
47
- #src = src.permute(1, 0, 2)
48
- #print("SRCCCCCCCC")
49
- #print(src.shape)
50
- #pos_embed = pos_embed.flatten(2).permute(2, 0, 1)
51
- #mask = mask.flatten(1)
52
- #print(num_decoder_layers)
53
-
54
- tgt = self.embeddings(tgt).permute(1, 0, 2)
55
- query_embed = self.embeddings.position_embeddings.weight.unsqueeze(1)
56
- query_embed = query_embed.repeat(1, bs, 1)
57
- #print("firstmyyyyyyyyyyyyyy")
58
- #print(tgt.shape)
59
- #print(tgt_mask.shape)
60
- #print(pos_embed.shape)
61
- #print(query_embed.shape)
62
- #print(generate_square_subsequent_mask(len(tgt)).to(tgt.device).shape)
63
- #print(src.shape)
64
-
65
- #memory = self.encoder(src, src_key_padding_mask=None, pos=None)
66
- #memory = self.encoder(src)
67
- #print("then....")
68
- #print(tgt_mask.shape)
69
- hs = self.decoder(tgt, src, memory_key_padding_mask=None, tgt_key_padding_mask=tgt_mask,
70
- pos=None, query_pos=query_embed,
71
- tgt_mask=generate_square_subsequent_mask(len(tgt)).to(tgt.device))
72
- #hs = self.decoder(tgt, memory, tgt_key_padding_mask=tgt_mask,query_pos=query_embed,tgt_mask=generate_square_subsequent_mask(len(tgt)).to(tgt.device))
73
-
74
- return hs
75
-
76
-
77
- class TransformerEncoder(nn.Module):
78
-
79
- def __init__(self, encoder_layer, num_layers, norm=None):
80
- super().__init__()
81
- self.layers = _get_clones(encoder_layer, num_layers)
82
- self.num_layers = num_layers
83
- self.norm = norm
84
-
85
- def forward(self, src,
86
- mask: Optional[Tensor] = None,
87
- src_key_padding_mask: Optional[Tensor] = None,
88
- pos: Optional[Tensor] = None):
89
- output = src
90
-
91
- for layer in self.layers:
92
- output = layer(output, src_mask=mask,
93
- src_key_padding_mask=src_key_padding_mask, pos=pos)
94
-
95
- if self.norm is not None:
96
- output = self.norm(output)
97
-
98
- return output
99
-
100
-
101
- class TransformerDecoder(nn.Module):
102
-
103
- def __init__(self, decoder_layer, num_layers, norm=None, return_intermediate=False):
104
- super().__init__()
105
- self.layers = _get_clones(decoder_layer, num_layers)
106
- self.num_layers = num_layers
107
- self.norm = norm
108
- self.return_intermediate = return_intermediate
109
-
110
- def forward(self, tgt, memory,
111
- tgt_mask: Optional[Tensor] = None,
112
- memory_mask: Optional[Tensor] = None,
113
- tgt_key_padding_mask: Optional[Tensor] = None,
114
- memory_key_padding_mask: Optional[Tensor] = None,
115
- pos: Optional[Tensor] = None,
116
- query_pos: Optional[Tensor] = None):
117
- output = tgt
118
-
119
- intermediate = []
120
-
121
- for layer in self.layers:
122
- output = layer(output, memory, tgt_mask=tgt_mask,
123
- memory_mask=memory_mask,
124
- tgt_key_padding_mask=tgt_key_padding_mask,
125
- memory_key_padding_mask=memory_key_padding_mask,
126
- pos=pos, query_pos=query_pos)
127
- if self.return_intermediate:
128
- intermediate.append(self.norm(output))
129
-
130
- if self.norm is not None:
131
- output = self.norm(output)
132
- if self.return_intermediate:
133
- intermediate.pop()
134
- intermediate.append(output)
135
-
136
- if self.return_intermediate:
137
- return torch.stack(intermediate)
138
-
139
- return output
140
-
141
-
142
- class TransformerEncoderLayer(nn.Module):
143
-
144
- def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1,
145
- activation="relu", normalize_before=False):
146
- super().__init__()
147
- self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
148
- # Implementation of Feedforward model
149
- self.linear1 = nn.Linear(d_model, dim_feedforward)
150
- self.dropout = nn.Dropout(dropout)
151
- self.linear2 = nn.Linear(dim_feedforward, d_model)
152
-
153
- self.norm1 = nn.LayerNorm(d_model)
154
- self.norm2 = nn.LayerNorm(d_model)
155
- self.dropout1 = nn.Dropout(dropout)
156
- self.dropout2 = nn.Dropout(dropout)
157
-
158
- self.activation = _get_activation_fn(activation)
159
- self.normalize_before = normalize_before
160
-
161
- def with_pos_embed(self, tensor, pos: Optional[Tensor]):
162
- return tensor if pos is None else tensor + pos
163
-
164
- def forward_post(self,
165
- src,
166
- src_mask: Optional[Tensor] = None,
167
- src_key_padding_mask: Optional[Tensor] = None,
168
- pos: Optional[Tensor] = None):
169
- q = k = self.with_pos_embed(src, pos)
170
- src2 = self.self_attn(q, k, value=src, attn_mask=src_mask,
171
- key_padding_mask=src_key_padding_mask)[0]
172
- src = src + self.dropout1(src2)
173
- src = self.norm1(src)
174
- src2 = self.linear2(self.dropout(self.activation(self.linear1(src))))
175
- src = src + self.dropout2(src2)
176
- src = self.norm2(src)
177
- return src
178
-
179
- def forward_pre(self, src,
180
- src_mask: Optional[Tensor] = None,
181
- src_key_padding_mask: Optional[Tensor] = None,
182
- pos: Optional[Tensor] = None):
183
- src2 = self.norm1(src)
184
- q = k = self.with_pos_embed(src2, pos)
185
- src2 = self.self_attn(q, k, value=src2, attn_mask=src_mask,
186
- key_padding_mask=src_key_padding_mask)[0]
187
- src = src + self.dropout1(src2)
188
- src2 = self.norm2(src)
189
- src2 = self.linear2(self.dropout(self.activation(self.linear1(src2))))
190
- src = src + self.dropout2(src2)
191
- return src
192
-
193
- def forward(self, src,
194
- src_mask: Optional[Tensor] = None,
195
- src_key_padding_mask: Optional[Tensor] = None,
196
- pos: Optional[Tensor] = None):
197
- if self.normalize_before:
198
- return self.forward_pre(src, src_mask, src_key_padding_mask, pos)
199
- return self.forward_post(src, src_mask, src_key_padding_mask, pos)
200
-
201
-
202
- class TransformerDecoderLayer(nn.Module):
203
-
204
- def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1,
205
- activation="relu", normalize_before=False):
206
- super().__init__()
207
- self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
208
- self.multihead_attn = nn.MultiheadAttention(
209
- d_model, nhead, dropout=dropout)
210
- # Implementation of Feedforward model
211
- self.linear1 = nn.Linear(d_model, dim_feedforward)
212
- self.dropout = nn.Dropout(dropout)
213
- self.linear2 = nn.Linear(dim_feedforward, d_model)
214
-
215
- self.norm1 = nn.LayerNorm(d_model)
216
- self.norm2 = nn.LayerNorm(d_model)
217
- self.norm3 = nn.LayerNorm(d_model)
218
- self.dropout1 = nn.Dropout(dropout)
219
- self.dropout2 = nn.Dropout(dropout)
220
- self.dropout3 = nn.Dropout(dropout)
221
-
222
- self.activation = _get_activation_fn(activation)
223
- self.normalize_before = normalize_before
224
-
225
-
226
- def with_pos_embed(self, tensor, pos: Optional[Tensor]):
227
- return tensor if pos is None else tensor + pos
228
-
229
- def forward_post(self, tgt, memory,
230
- tgt_mask: Optional[Tensor] = None,
231
- memory_mask: Optional[Tensor] = None,
232
- tgt_key_padding_mask: Optional[Tensor] = None,
233
- memory_key_padding_mask: Optional[Tensor] = None,
234
- pos: Optional[Tensor] = None,
235
- query_pos: Optional[Tensor] = None):
236
- #print(tgt.shape)
237
- #print(query_pos.shape)
238
-
239
- q = k = self.with_pos_embed(tgt, query_pos)
240
- tgt2 = self.self_attn(q, k, value=tgt, attn_mask=tgt_mask,
241
- key_padding_mask=tgt_key_padding_mask)[0]
242
- tgt = tgt + self.dropout1(tgt2)
243
- tgt = self.norm1(tgt)
244
- tgt2 = self.multihead_attn(query=self.with_pos_embed(tgt, query_pos),
245
- key=self.with_pos_embed(memory, pos),
246
- value=memory, attn_mask=memory_mask,
247
- key_padding_mask=memory_key_padding_mask)[0]
248
- tgt = tgt + self.dropout2(tgt2)
249
- tgt = self.norm2(tgt)
250
- tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt))))
251
- tgt = tgt + self.dropout3(tgt2)
252
- tgt = self.norm3(tgt)
253
- return tgt
254
-
255
- def forward_pre(self, tgt, memory,
256
- tgt_mask: Optional[Tensor] = None,
257
- memory_mask: Optional[Tensor] = None,
258
- tgt_key_padding_mask: Optional[Tensor] = None,
259
- memory_key_padding_mask: Optional[Tensor] = None,
260
- pos: Optional[Tensor] = None,
261
- query_pos: Optional[Tensor] = None):
262
- tgt2 = self.norm1(tgt)
263
- q = k = self.with_pos_embed(tgt2, query_pos)
264
- tgt2 = self.self_attn(q, k, value=tgt2, attn_mask=tgt_mask,
265
- key_padding_mask=tgt_key_padding_mask)[0]
266
- tgt = tgt + self.dropout1(tgt2)
267
- tgt2 = self.norm2(tgt)
268
- tgt2 = self.multihead_attn(query=self.with_pos_embed(tgt2, query_pos),
269
- key=self.with_pos_embed(memory, pos),
270
- value=memory, attn_mask=memory_mask,
271
- key_padding_mask=memory_key_padding_mask)[0]
272
- tgt = tgt + self.dropout2(tgt2)
273
- tgt2 = self.norm3(tgt)
274
- tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt2))))
275
- tgt = tgt + self.dropout3(tgt2)
276
- return tgt
277
-
278
- def forward(self, tgt, memory,
279
- tgt_mask: Optional[Tensor] = None,
280
- memory_mask: Optional[Tensor] = None,
281
- tgt_key_padding_mask: Optional[Tensor] = None,
282
- memory_key_padding_mask: Optional[Tensor] = None,
283
- pos: Optional[Tensor] = None,
284
- query_pos: Optional[Tensor] = None):
285
- if self.normalize_before:
286
- return self.forward_pre(tgt, memory, tgt_mask, memory_mask,
287
- tgt_key_padding_mask, memory_key_padding_mask, pos, query_pos)
288
- return self.forward_post(tgt, memory, tgt_mask, memory_mask,
289
- tgt_key_padding_mask, memory_key_padding_mask, pos, query_pos)
290
-
291
-
292
- class DecoderEmbeddings(nn.Module):
293
- def __init__(self, config):
294
- super().__init__()
295
- self.word_embeddings = nn.Embedding(
296
- config.vocab_size, config.hidden_dim, padding_idx=config.pad_token_id)
297
- self.position_embeddings = nn.Embedding(
298
- config.max_position_embeddings, config.hidden_dim
299
- )
300
-
301
- self.LayerNorm = torch.nn.LayerNorm(
302
- config.hidden_dim, eps=config.layer_norm_eps)
303
- self.dropout = nn.Dropout(config.dropout)
304
-
305
- def forward(self, x):
306
- input_shape = x.size()
307
- x=x.long()
308
- #print(x.shape)
309
- seq_length = input_shape[1]
310
- device = x.device
311
-
312
- position_ids = torch.arange(
313
- seq_length, dtype=torch.long, device=device)
314
- position_ids = position_ids.unsqueeze(0).expand(input_shape)
315
- input_embeds = self.word_embeddings(x)
316
- position_embeds = self.position_embeddings(position_ids)
317
-
318
-
319
- embeddings = input_embeds + position_embeds
320
- embeddings = self.LayerNorm(embeddings)
321
- embeddings = self.dropout(embeddings)
322
-
323
- #print(embeddings)
324
-
325
- return embeddings
326
-
327
-
328
- def _get_clones(module, N):
329
- return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
330
-
331
-
332
- def _get_activation_fn(activation):
333
- """Return an activation function given a string"""
334
- if activation == "relu":
335
- return F.relu
336
- if activation == "gelu":
337
- return F.gelu
338
- if activation == "glu":
339
- return F.glu
340
- raise RuntimeError(F"activation should be relu/gelu, not {activation}.")
341
-
342
-
343
- def generate_square_subsequent_mask(sz):
344
- r"""Generate a square mask for the sequence. The masked positions are filled with float('-inf').
345
- Unmasked positions are filled with float(0.0).
346
- """
347
- mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1)
348
- mask = mask.float().masked_fill(mask == 0, float(
349
- '-inf')).masked_fill(mask == 1, float(0.0))
350
- return mask
351
-
352
-
353
- def build_transformer(config):
354
- return Transformer_Caption(
355
- config,
356
- d_model=config.hidden_dim,
357
- dropout=config.dropout,
358
- nhead=config.nheads,
359
- dim_feedforward=config.dim_feedforward,
360
- num_encoder_layers=config.enc_layers,
361
- num_decoder_layers=config.dec_layers,
362
- normalize_before=config.pre_norm,
363
- return_intermediate_dec=False,
364
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/detectron2/projects/DensePose/densepose/config.py DELETED
@@ -1,57 +0,0 @@
1
- # -*- coding = utf-8 -*-
2
- # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
3
-
4
- from detectron2.config import CfgNode as CN
5
-
6
-
7
- def add_densepose_config(cfg):
8
- """
9
- Add config for densepose head.
10
- """
11
- _C = cfg
12
-
13
- _C.MODEL.DENSEPOSE_ON = True
14
-
15
- _C.MODEL.ROI_DENSEPOSE_HEAD = CN()
16
- _C.MODEL.ROI_DENSEPOSE_HEAD.NAME = ""
17
- _C.MODEL.ROI_DENSEPOSE_HEAD.NUM_STACKED_CONVS = 8
18
- # Number of parts used for point labels
19
- _C.MODEL.ROI_DENSEPOSE_HEAD.NUM_PATCHES = 24
20
- _C.MODEL.ROI_DENSEPOSE_HEAD.DECONV_KERNEL = 4
21
- _C.MODEL.ROI_DENSEPOSE_HEAD.CONV_HEAD_DIM = 512
22
- _C.MODEL.ROI_DENSEPOSE_HEAD.CONV_HEAD_KERNEL = 3
23
- _C.MODEL.ROI_DENSEPOSE_HEAD.UP_SCALE = 2
24
- _C.MODEL.ROI_DENSEPOSE_HEAD.HEATMAP_SIZE = 112
25
- _C.MODEL.ROI_DENSEPOSE_HEAD.POOLER_TYPE = "ROIAlignV2"
26
- _C.MODEL.ROI_DENSEPOSE_HEAD.POOLER_RESOLUTION = 28
27
- _C.MODEL.ROI_DENSEPOSE_HEAD.POOLER_SAMPLING_RATIO = 2
28
- _C.MODEL.ROI_DENSEPOSE_HEAD.NUM_COARSE_SEGM_CHANNELS = 2 # 15 or 2
29
- # Overlap threshold for an RoI to be considered foreground (if >= FG_IOU_THRESHOLD)
30
- _C.MODEL.ROI_DENSEPOSE_HEAD.FG_IOU_THRESHOLD = 0.7
31
- # Loss weights for annotation masks.(14 Parts)
32
- _C.MODEL.ROI_DENSEPOSE_HEAD.INDEX_WEIGHTS = 5.0
33
- # Loss weights for surface parts. (24 Parts)
34
- _C.MODEL.ROI_DENSEPOSE_HEAD.PART_WEIGHTS = 1.0
35
- # Loss weights for UV regression.
36
- _C.MODEL.ROI_DENSEPOSE_HEAD.POINT_REGRESSION_WEIGHTS = 0.01
37
- # For Decoder
38
- _C.MODEL.ROI_DENSEPOSE_HEAD.DECODER_ON = True
39
- _C.MODEL.ROI_DENSEPOSE_HEAD.DECODER_NUM_CLASSES = 256
40
- _C.MODEL.ROI_DENSEPOSE_HEAD.DECODER_CONV_DIMS = 256
41
- _C.MODEL.ROI_DENSEPOSE_HEAD.DECODER_NORM = ""
42
- _C.MODEL.ROI_DENSEPOSE_HEAD.DECODER_COMMON_STRIDE = 4
43
- # For DeepLab head
44
- _C.MODEL.ROI_DENSEPOSE_HEAD.DEEPLAB = CN()
45
- _C.MODEL.ROI_DENSEPOSE_HEAD.DEEPLAB.NORM = "GN"
46
- _C.MODEL.ROI_DENSEPOSE_HEAD.DEEPLAB.NONLOCAL_ON = 0
47
- # Confidences
48
- # Enable learning confidences (variances) along with the actual values
49
- _C.MODEL.ROI_DENSEPOSE_HEAD.UV_CONFIDENCE = CN({"ENABLED": False})
50
- # UV confidence lower bound
51
- _C.MODEL.ROI_DENSEPOSE_HEAD.UV_CONFIDENCE.EPSILON = 0.01
52
- # Statistical model type for confidence learning, possible values:
53
- # - "iid_iso": statistically independent identically distributed residuals
54
- # with isotropic covariance
55
- # - "indep_aniso": statistically independent residuals with anisotropic
56
- # covariances
57
- _C.MODEL.ROI_DENSEPOSE_HEAD.UV_CONFIDENCE.TYPE = "iid_iso"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/CVPR/LIVE/pybind11/include/pybind11/common.h DELETED
@@ -1,2 +0,0 @@
1
- #include "detail/common.h"
2
- #warning "Including 'common.h' is deprecated. It will be removed in v3.0. Use 'pybind11.h'."
 
 
 
spaces/CVPR/LIVE/pybind11/tests/test_pickling.py DELETED
@@ -1,46 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- import pytest
3
-
4
- import env # noqa: F401
5
-
6
- from pybind11_tests import pickling as m
7
-
8
- try:
9
- import cPickle as pickle # Use cPickle on Python 2.7
10
- except ImportError:
11
- import pickle
12
-
13
-
14
- @pytest.mark.parametrize("cls_name", ["Pickleable", "PickleableNew"])
15
- def test_roundtrip(cls_name):
16
- cls = getattr(m, cls_name)
17
- p = cls("test_value")
18
- p.setExtra1(15)
19
- p.setExtra2(48)
20
-
21
- data = pickle.dumps(p, 2) # Must use pickle protocol >= 2
22
- p2 = pickle.loads(data)
23
- assert p2.value() == p.value()
24
- assert p2.extra1() == p.extra1()
25
- assert p2.extra2() == p.extra2()
26
-
27
-
28
- @pytest.mark.xfail("env.PYPY")
29
- @pytest.mark.parametrize("cls_name", ["PickleableWithDict", "PickleableWithDictNew"])
30
- def test_roundtrip_with_dict(cls_name):
31
- cls = getattr(m, cls_name)
32
- p = cls("test_value")
33
- p.extra = 15
34
- p.dynamic = "Attribute"
35
-
36
- data = pickle.dumps(p, pickle.HIGHEST_PROTOCOL)
37
- p2 = pickle.loads(data)
38
- assert p2.value == p.value
39
- assert p2.extra == p.extra
40
- assert p2.dynamic == p.dynamic
41
-
42
-
43
- def test_enum_pickle():
44
- from pybind11_tests import enums as e
45
- data = pickle.dumps(e.EOne, 2)
46
- assert e.EOne == pickle.loads(data)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/CVPR/LIVE/thrust/thrust/system/omp/detail/unique.h DELETED
@@ -1,59 +0,0 @@
1
- /*
2
- * Copyright 2008-2013 NVIDIA Corporation
3
- *
4
- * Licensed under the Apache License, Version 2.0 (the "License");
5
- * you may not use this file except in compliance with the License.
6
- * You may obtain a copy of the License at
7
- *
8
- * http://www.apache.org/licenses/LICENSE-2.0
9
- *
10
- * Unless required by applicable law or agreed to in writing, software
11
- * distributed under the License is distributed on an "AS IS" BASIS,
12
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- * See the License for the specific language governing permissions and
14
- * limitations under the License.
15
- */
16
-
17
- #pragma once
18
-
19
- #include <thrust/detail/config.h>
20
- #include <thrust/system/omp/detail/execution_policy.h>
21
- #include <thrust/pair.h>
22
-
23
- namespace thrust
24
- {
25
- namespace system
26
- {
27
- namespace omp
28
- {
29
- namespace detail
30
- {
31
-
32
-
33
- template<typename DerivedPolicy,
34
- typename ForwardIterator,
35
- typename BinaryPredicate>
36
- ForwardIterator unique(execution_policy<DerivedPolicy> &exec,
37
- ForwardIterator first,
38
- ForwardIterator last,
39
- BinaryPredicate binary_pred);
40
-
41
-
42
- template<typename DerivedPolicy,
43
- typename InputIterator,
44
- typename OutputIterator,
45
- typename BinaryPredicate>
46
- OutputIterator unique_copy(execution_policy<DerivedPolicy> &exec,
47
- InputIterator first,
48
- InputIterator last,
49
- OutputIterator output,
50
- BinaryPredicate binary_pred);
51
-
52
-
53
- } // end namespace detail
54
- } // end namespace omp
55
- } // end namespace system
56
- } // end namespace thrust
57
-
58
- #include <thrust/system/omp/detail/unique.inl>
59
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/CVPR/MonoScene/monoscene/DDR.py DELETED
@@ -1,139 +0,0 @@
1
- """
2
- Most of the code in this file is taken from https://github.com/waterljwant/SSC/blob/master/models/DDR.py
3
- """
4
-
5
- import torch
6
- import torch.nn as nn
7
- import torch.nn.functional as F
8
-
9
-
10
- class SimpleRB(nn.Module):
11
- def __init__(self, in_channel, norm_layer, bn_momentum):
12
- super(SimpleRB, self).__init__()
13
- self.path = nn.Sequential(
14
- nn.Conv3d(in_channel, in_channel, kernel_size=3, padding=1, bias=False),
15
- norm_layer(in_channel, momentum=bn_momentum),
16
- nn.ReLU(),
17
- nn.Conv3d(in_channel, in_channel, kernel_size=3, padding=1, bias=False),
18
- norm_layer(in_channel, momentum=bn_momentum),
19
- )
20
- self.relu = nn.ReLU()
21
-
22
- def forward(self, x):
23
- residual = x
24
- conv_path = self.path(x)
25
- out = residual + conv_path
26
- out = self.relu(out)
27
- return out
28
-
29
-
30
- """
31
- 3D Residual Block,3x3x3 conv ==> 3 smaller 3D conv, refered from DDRNet
32
- """
33
-
34
-
35
- class Bottleneck3D(nn.Module):
36
- def __init__(
37
- self,
38
- inplanes,
39
- planes,
40
- norm_layer,
41
- stride=1,
42
- dilation=[1, 1, 1],
43
- expansion=4,
44
- downsample=None,
45
- fist_dilation=1,
46
- multi_grid=1,
47
- bn_momentum=0.0003,
48
- ):
49
- super(Bottleneck3D, self).__init__()
50
- # often,planes = inplanes // 4
51
- self.expansion = expansion
52
- self.conv1 = nn.Conv3d(inplanes, planes, kernel_size=1, bias=False)
53
- self.bn1 = norm_layer(planes, momentum=bn_momentum)
54
- self.conv2 = nn.Conv3d(
55
- planes,
56
- planes,
57
- kernel_size=(1, 1, 3),
58
- stride=(1, 1, stride),
59
- dilation=(1, 1, dilation[0]),
60
- padding=(0, 0, dilation[0]),
61
- bias=False,
62
- )
63
- self.bn2 = norm_layer(planes, momentum=bn_momentum)
64
- self.conv3 = nn.Conv3d(
65
- planes,
66
- planes,
67
- kernel_size=(1, 3, 1),
68
- stride=(1, stride, 1),
69
- dilation=(1, dilation[1], 1),
70
- padding=(0, dilation[1], 0),
71
- bias=False,
72
- )
73
- self.bn3 = norm_layer(planes, momentum=bn_momentum)
74
- self.conv4 = nn.Conv3d(
75
- planes,
76
- planes,
77
- kernel_size=(3, 1, 1),
78
- stride=(stride, 1, 1),
79
- dilation=(dilation[2], 1, 1),
80
- padding=(dilation[2], 0, 0),
81
- bias=False,
82
- )
83
- self.bn4 = norm_layer(planes, momentum=bn_momentum)
84
- self.conv5 = nn.Conv3d(
85
- planes, planes * self.expansion, kernel_size=(1, 1, 1), bias=False
86
- )
87
- self.bn5 = norm_layer(planes * self.expansion, momentum=bn_momentum)
88
-
89
- self.relu = nn.ReLU(inplace=False)
90
- self.relu_inplace = nn.ReLU(inplace=True)
91
- self.downsample = downsample
92
- self.dilation = dilation
93
- self.stride = stride
94
-
95
- self.downsample2 = nn.Sequential(
96
- nn.AvgPool3d(kernel_size=(1, stride, 1), stride=(1, stride, 1)),
97
- nn.Conv3d(planes, planes, kernel_size=1, stride=1, bias=False),
98
- norm_layer(planes, momentum=bn_momentum),
99
- )
100
- self.downsample3 = nn.Sequential(
101
- nn.AvgPool3d(kernel_size=(stride, 1, 1), stride=(stride, 1, 1)),
102
- nn.Conv3d(planes, planes, kernel_size=1, stride=1, bias=False),
103
- norm_layer(planes, momentum=bn_momentum),
104
- )
105
- self.downsample4 = nn.Sequential(
106
- nn.AvgPool3d(kernel_size=(stride, 1, 1), stride=(stride, 1, 1)),
107
- nn.Conv3d(planes, planes, kernel_size=1, stride=1, bias=False),
108
- norm_layer(planes, momentum=bn_momentum),
109
- )
110
-
111
- def forward(self, x):
112
- residual = x
113
-
114
- out1 = self.relu(self.bn1(self.conv1(x)))
115
- out2 = self.bn2(self.conv2(out1))
116
- out2_relu = self.relu(out2)
117
-
118
- out3 = self.bn3(self.conv3(out2_relu))
119
- if self.stride != 1:
120
- out2 = self.downsample2(out2)
121
- out3 = out3 + out2
122
- out3_relu = self.relu(out3)
123
-
124
- out4 = self.bn4(self.conv4(out3_relu))
125
- if self.stride != 1:
126
- out2 = self.downsample3(out2)
127
- out3 = self.downsample4(out3)
128
- out4 = out4 + out2 + out3
129
-
130
- out4_relu = self.relu(out4)
131
- out5 = self.bn5(self.conv5(out4_relu))
132
-
133
- if self.downsample is not None:
134
- residual = self.downsample(x)
135
-
136
- out = out5 + residual
137
- out_relu = self.relu(out)
138
-
139
- return out_relu