parquet-converter commited on
Commit
97b36c7
·
1 Parent(s): 64cebd0

Update parquet files (step 94 of 397)

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/0x7194633/nllb-1.3B-demo/app.py +0 -83
  2. spaces/1acneusushi/gradio-2dmoleculeeditor/data/Apocalypto Hollywood Movie Hindi Dubbing Hd Mp4 238 Watch Online or Download Now.md +0 -193
  3. spaces/1acneusushi/gradio-2dmoleculeeditor/data/Download MPLAB XC32 Keygen and Enjoy the Full Potential of the Compiler.md +0 -112
  4. spaces/1gistliPinn/ChatGPT4/Examples/Apowersoft Screen Capture Pro V1.1.3 Incl REPACK Keygen.md +0 -11
  5. spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Download Garena Free Fire APK for Android - Apktodo.com.md +0 -124
  6. spaces/1phancelerku/anime-remove-background/DBZ RPG Join Goku and Friends in the Ultimate Dragon Ball Adventure.md +0 -131
  7. spaces/1phancelerku/anime-remove-background/Download My Eternal Season 5 Episode 1 - The Best Filipino Drama Ever.md +0 -120
  8. spaces/4Taps/SadTalker/src/utils/face_enhancer.py +0 -60
  9. spaces/801artistry/RVC801/infer/lib/infer_pack/modules.py +0 -521
  10. spaces/801artistry/RVC801/tools/calc_rvc_model_similarity.py +0 -96
  11. spaces/AIFILMS/generate_human_motion/pyrender/pyrender/trackball.py +0 -216
  12. spaces/AIGC-Audio/AudioGPT/text_to_speech/modules/tts/syntaspeech/multi_window_disc.py +0 -136
  13. spaces/AIGC-Audio/AudioGPT/text_to_speech/modules/vocoder/hifigan/mel_utils.py +0 -80
  14. spaces/AIGC-Audio/AudioGPT/text_to_speech/utils/commons/multiprocess_utils.py +0 -130
  15. spaces/ARTeLab/DTM_Estimation_SRandD/README.md +0 -12
  16. spaces/ASJMO/freegpt/client/css/label.css +0 -16
  17. spaces/ASJMO/freegpt/client/js/highlight.min.js +0 -0
  18. spaces/AchyuthGamer/OpenGPT-Chat-UI/src/lib/utils/models.ts +0 -4
  19. spaces/AgentVerse/agentVerse/agentverse/agents/tasksolving_agent/evaluator.py +0 -86
  20. spaces/AlexWang/lama/fetch_data/places_standard_train_prepare.sh +0 -16
  21. spaces/Aloento/9Nine-PITS/text/frontend/zh_normalization/num.py +0 -238
  22. spaces/Amrrs/DragGan-Inversion/torch_utils/misc.py +0 -295
  23. spaces/Amrrs/DragGan-Inversion/visualizer_drag_gradio.py +0 -934
  24. spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/en/api/pipelines/audio_diffusion.md +0 -37
  25. spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/en/api/pipelines/overview.md +0 -36
  26. spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/en/api/pipelines/stable_diffusion/overview.md +0 -180
  27. spaces/Anonymous-sub/Rerender/ControlNet/annotator/uniformer/mmcv/parallel/collate.py +0 -84
  28. spaces/AriaMei/TTSdemo/utils.py +0 -267
  29. spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_internal/metadata/importlib/_compat.py +0 -55
  30. spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/_vendor/tomli/_types.py +0 -10
  31. spaces/BIOML-SVM/SVM/msa.py +0 -62
  32. spaces/Benson/text-generation/Examples/Ataque Areo Comando Mod Apk.md +0 -92
  33. spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/rich/jupyter.py +0 -101
  34. spaces/Billyosoro/ESRGAN/tests/test_model.py +0 -126
  35. spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/detectron2/docs/tutorials/datasets.md +0 -214
  36. spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/detectron2/projects/DensePose/densepose/dataset_mapper.py +0 -118
  37. spaces/CVPR/LIVE/model_download/yolov5_model_p6_all.sh +0 -8
  38. spaces/CVPR/LIVE/thrust/internal/test/thrust_nightly.pl +0 -600
  39. spaces/CVPR/LIVE/thrust/thrust/detail/type_traits/iterator/is_output_iterator.h +0 -66
  40. spaces/CVPR/LIVE/thrust/thrust/system/cpp/detail/extrema.h +0 -23
  41. spaces/Chaitanya01/InvestingPlatform/setup.sh +0 -13
  42. spaces/Chomkwoy/Nilkessye/cpool_new/setup.py +0 -14
  43. spaces/ChristopherMarais/Andrew_AI-BB_classification-beta/mysite/andrew_alpha/admin.py +0 -3
  44. spaces/CognitiveLabs/Research-Assistant/statics/style.py +0 -117
  45. spaces/Cong723/gpt-academic-public/crazy_functions/test_project/python/dqn/__init__.py +0 -2
  46. spaces/Cropinky/gpt2-rap-songs/README.md +0 -33
  47. spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/gradio/processing_utils.py +0 -546
  48. spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/huggingface_hub/_commit_api.py +0 -632
  49. spaces/Daniil-plotnikov/Daniil-plotnikov-russian-vision-v4/app.py +0 -3
  50. spaces/Datasculptor/LoRA-DreamBooth-Training-UI/trainer.py +0 -166
spaces/0x7194633/nllb-1.3B-demo/app.py DELETED
@@ -1,83 +0,0 @@
1
- import os
2
- import torch
3
- import gradio as gr
4
- import time
5
- from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline
6
- from flores200_codes import flores_codes
7
-
8
-
9
- def load_models():
10
- # build model and tokenizer
11
- model_name_dict = {'nllb-distilled-1.3B': 'facebook/nllb-200-distilled-1.3B'}
12
-
13
- model_dict = {}
14
-
15
- for call_name, real_name in model_name_dict.items():
16
- print('\tLoading model: %s' % call_name)
17
- model = AutoModelForSeq2SeqLM.from_pretrained(real_name)
18
- tokenizer = AutoTokenizer.from_pretrained(real_name)
19
- model_dict[call_name+'_model'] = model
20
- model_dict[call_name+'_tokenizer'] = tokenizer
21
-
22
- return model_dict
23
-
24
-
25
- def translation(source, target, text):
26
- if len(model_dict) == 2:
27
- model_name = 'nllb-distilled-1.3B'
28
-
29
- start_time = time.time()
30
- source = flores_codes[source]
31
- target = flores_codes[target]
32
-
33
- model = model_dict[model_name + '_model']
34
- tokenizer = model_dict[model_name + '_tokenizer']
35
-
36
- translator = pipeline('translation', model=model, tokenizer=tokenizer, src_lang=source, tgt_lang=target)
37
- output = translator(text, max_length=400)
38
-
39
- end_time = time.time()
40
-
41
- output = output[0]['translation_text']
42
- result = {'inference_time': end_time - start_time,
43
- 'source': source,
44
- 'target': target,
45
- 'result': output}
46
- return result
47
-
48
-
49
- if __name__ == '__main__':
50
- print('\tinit models')
51
-
52
- global model_dict
53
-
54
- model_dict = load_models()
55
-
56
- # define gradio demo
57
- lang_codes = list(flores_codes.keys())
58
- #inputs = [gr.inputs.Radio(['nllb-distilled-600M', 'nllb-1.3B', 'nllb-distilled-1.3B'], label='NLLB Model'),
59
- inputs = [gr.inputs.Dropdown(lang_codes, default='English', label='Source'),
60
- gr.inputs.Dropdown(lang_codes, default='Korean', label='Target'),
61
- gr.inputs.Textbox(lines=5, label="Input text"),
62
- ]
63
-
64
- outputs = gr.outputs.JSON()
65
-
66
- title = "NLLB distilled 1.3B demo"
67
-
68
- demo_status = "Demo is running on CPU"
69
- description = f"Details: https://github.com/facebookresearch/fairseq/tree/nllb. {demo_status}"
70
- examples = [
71
- ['English', 'Korean', 'Hi. nice to meet you']
72
- ]
73
-
74
- gr.Interface(translation,
75
- inputs,
76
- outputs,
77
- title=title,
78
- description=description,
79
- examples=examples,
80
- examples_per_page=50,
81
- ).launch()
82
-
83
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1acneusushi/gradio-2dmoleculeeditor/data/Apocalypto Hollywood Movie Hindi Dubbing Hd Mp4 238 Watch Online or Download Now.md DELETED
@@ -1,193 +0,0 @@
1
-
2
- <h1>Apocalypto: A Thrilling Adventure Movie Set in Ancient Maya</h1>
3
- <p>If you are looking for a movie that will take you on a wild ride through a fascinating historical period with breathtaking action scenes and captivating characters, then you should watch <strong>Apocalypto</strong>. This movie is a historical fiction action-adventure drama film directed by Mel Gibson and released in 2006. It tells the story of a young Maya man who escapes from being sacrificed by a ruthless enemy tribe and tries to save his family and his people from destruction. In this article, we will explore everything you need to know about this movie, including its plot, genre, director, cast, release date, critical reception, Hindi dubbing, and HD Mp4 238 format.</p>
4
- <h2>Apocalypto Hollywood Movie Hindi Dubbing Hd Mp4 238</h2><br /><p><b><b>DOWNLOAD</b> === <a href="https://byltly.com/2uKy1i">https://byltly.com/2uKy1i</a></b></p><br /><br />
5
- <h2>The Plot of Apocalypto</h2>
6
- <p>The movie is divided into three acts:</p>
7
- <ol>
8
- <li>The Raid</li>
9
- <p>In this act, we are introduced to Jaguar Paw (Rudy Youngblood), a hunter from a peaceful Maya village in the rainforest. He lives with his pregnant wife Seven (Dalia Hernandez) and his young son Turtles Run (Carlos Emilio Baez). One day, his village is attacked by a group of warriors led by Zero Wolf (Raoul Trujillo), who are looking for captives to sacrifice to their gods. and son in a deep pit before being captured along with many others.</p>
10
- <li>The Escape</li>
11
- <p>In this act, we follow Jaguar Paw's journey as he is taken to a nearby city where he witnesses the horrors of human sacrifice, slavery, and disease. He also meets a young girl (María Isabel Díaz) who prophesies that the end of their world is near. Jaguar Paw is chosen as one of the victims to be sacrificed on top of a pyramid, but before his heart can be ripped out, a solar eclipse occurs, which is interpreted as a sign from the gods. The high priest (Fernando Hernandez) decides to spare the remaining captives and orders them to be killed by Zero Wolf's men in a game where they have to run through a field while being shot at by arrows. Jaguar Paw manages to escape and kills one of Zero Wolf's sons in retaliation. This sparks a relentless chase through the jungle as Jaguar Paw tries to outrun his pursuers and reach his wife and son.</p>
12
- <li>The Eclipse</li>
13
- <p>In this act, we witness Jaguar Paw's survival skills and courage as he faces various obstacles and enemies along his way. He also encounters some friendly animals and plants that help him heal his wounds and find his way back home. He finally arrives at his village and rescues his wife and son from the pit, which is flooded by rainwater. He then confronts Zero Wolf and kills him in a brutal fight. He also sees some Spanish ships arriving on the coast, which signals the arrival of a new era. He decides to leave his village and take his family deeper into the forest, where they can start anew.</p>
14
- </ol>
15
- <h2>The Genre of Apocalypto</h2>
16
- <h3>Historical Fiction</h3>
17
- <p>The movie is set in ancient Maya civilization, which flourished in Mesoamerica from around 2000 BC to 1697 AD. The movie depicts various aspects of Maya culture, such as their religion, architecture, art, writing, mathematics, astronomy, calendar, and warfare. However, the movie also takes some creative liberties with historical facts and adds some fictional elements to create a more dramatic and engaging story. For example,</p>
18
- <p>Apocalypto full movie in Hindi dubbed hd download mp4<br />
19
- Apocalypto Hindi dubbing hd mp4 238 watch online free<br />
20
- Apocalypto Hollywood movie Hindi voice over hd mp4 238<br />
21
- Apocalypto Hindi dubbed hd mp4 238 torrent magnet link<br />
22
- Apocalypto movie in Hindi hd mp4 238 free download filmywap<br />
23
- Apocalypto Hollywood film Hindi dubbing hd mp4 238 streaming<br />
24
- Apocalypto Hindi dubbing hd mp4 238 subtitles download<br />
25
- Apocalypto Hollywood movie in Hindi hd mp4 238 480p 720p 1080p<br />
26
- Apocalypto Hindi dubbing hd mp4 238 full cast and crew<br />
27
- Apocalypto movie Hindi dubbing hd mp4 238 review and rating<br />
28
- Apocalypto Hollywood movie Hindi dubbed hd mp4 238 trailer<br />
29
- Apocalypto Hindi dubbing hd mp4 238 release date and box office<br />
30
- Apocalypto Hollywood movie in Hindi hd mp4 238 plot summary and spoilers<br />
31
- Apocalypto Hindi dubbing hd mp4 238 behind the scenes and making of<br />
32
- Apocalypto movie Hindi dubbed hd mp4 238 facts and trivia<br />
33
- Apocalypto Hollywood film Hindi dubbing hd mp4 238 awards and nominations<br />
34
- Apocalypto Hindi dubbing hd mp4 238 director's cut and deleted scenes<br />
35
- Apocalypto Hollywood movie in Hindi hd mp4 238 soundtrack and score<br />
36
- Apocalypto Hindi dubbing hd mp4 238 best scenes and quotes<br />
37
- Apocalypto movie Hindi dubbed hd mp4 238 analysis and interpretation<br />
38
- Apocalypto Hollywood movie Hindi dubbing hd mp4 238 genre and themes<br />
39
- Apocalypto Hindi dubbing hd mp4 238 historical accuracy and criticism<br />
40
- Apocalypto Hollywood movie in Hindi hd mp4 238 sequel and prequel<br />
41
- Apocalypto Hindi dubbing hd mp4 238 comparison and contrast with other movies<br />
42
- Apocalypto movie Hindi dubbed hd mp4 238 fan theories and speculations<br />
43
- Apocalypto Hollywood film Hindi dubbing hd mp4 238 merchandise and collectibles<br />
44
- Apocalypto Hindi dubbing hd mp4 238 memes and jokes<br />
45
- Apocalypto Hollywood movie in Hindi hd mp4 238 fan art and cosplay<br />
46
- Apocalypto Hindi dubbing hd mp4 238 fan fiction and crossover<br />
47
- Apocalypto movie Hindi dubbed hd mp4 238 remake and reboot<br />
48
- Apocalypto Hollywood movie Hindi dubbing hd mp4 238 Netflix and Amazon Prime availability<br />
49
- Apocalypto Hindi dubbing hd mp4 238 DVD and Blu-ray features and extras<br />
50
- Apocalypto Hollywood movie in Hindi hd mp4 238 IMDB and Rotten Tomatoes ratings<br />
51
- Apocalypto Hindi dubbing hd mp4 238 Metacritic and Roger Ebert reviews<br />
52
- Apocalypto movie Hindi dubbed hd mp4 238 Wikipedia and Quora information<br />
53
- Apocalypto Hollywood film Hindi dubbing hd mp4 238 Reddit and Twitter discussions<br />
54
- Apocalypto Hindi dubbing hd mp4 238 YouTube and TikTok videos<br />
55
- Apocalypto Hollywood movie in Hindi hd mp4 238 Instagram and Facebook posts<br />
56
- Apocalypto Hindi dubbing hd mp4 238 Pinterest and Tumblr images<br />
57
- Apocalypto movie Hindi dubbed hd mp4 238 Spotify and Apple Music playlists</p>
58
- <ul>
59
- <li>The movie does not specify when or where exactly it takes place,</li>
60
- <li>The Maya city shown in the movie is a composite of different sites,</li>
61
- <li>The Maya did not practice mass human sacrifice as shown in the movie,</li>
62
- <li>The solar eclipse that saves Jaguar Paw was not historically accurate,</li>
63
- <li>The Spanish ships that appear at the end were not the first ones to reach Mesoamerica.</li>
64
- </ul>
65
- <p>Therefore, the movie should not be taken as an accurate representation of Maya history, but rather as an artistic interpretation that uses history as a backdrop for an exciting adventure story.</p>
66
- <h3>Action-Adventure</h3>
67
- <p>The movie is also an action-adventure film that delivers thrilling action sequences and suspenseful chases throughout its runtime. The movie showcases various types of action scenes, such as:</p>
68
- <ul>
69
- <li>Hand-to-hand combat,</li>
70
- <li>Archery,</li>
71
- <li>Knife throwing,</li>
72
- <li>Spear throwing,</li>
73
- <li>Booby traps,</li>
74
- <li>Animal attacks,</li>
75
- <li>Natural disasters,</li>
76
- <li>Waterfalls,</li>
77
- <li>Quicksand,</li>
78
- <li>Crocodiles,</li>
79
- <li>Jaguars,</li>
80
- <li>Bees.</li>
81
- </ul>
82
- <p>The movie also uses minimal dialogue and relies mostly on visual storytelling and sound effects to create tension and emotion. The movie has been praised for its realistic and visceral depiction of violence and gore, as well as its stunning cinematography and editing that capture the beauty and danger of the natural environment.</p>
83
- <h3>Drama</h3>
84
- <p>The movie is not only an action-packed spectacle, but also a drama that explores themes such as survival, family, courage, sacrifice, and faith through its characters and their struggles. The movie portrays the contrast between the peaceful and harmonious life of Jaguar Paw's village and the cruel and chaotic life of Zero Wolf's city. The movie also shows how Jaguar Paw's love for his wife and son motivates him to overcome all odds and challenges. The movie also raises questions about the meaning and purpose of life, the role of fate and destiny, the value of culture and tradition, and the impact of change and progress on human societies. The movie has been criticized for its negative and stereotypical portrayal of indigenous people as savage and barbaric, as well as its implicit endorsement of colonialism and Christianity.</p>
85
- <h2>The Director of Apocalypto</h2>
86
- <p>The movie was directed by Mel Gibson, who is also known for his roles in movies such as Braveheart, Lethal Weapon, Mad Max, The Passion of the Christ, and Hacksaw Ridge. Gibson is an Australian-American actor, filmmaker, and producer who has won several awards and accolades for his work. He is also known for his controversial views and statements on politics, religion, race, gender, and sexuality. He has been accused of anti-Semitism, homophobia, misogyny, racism, domestic violence, and alcoholism. He has also faced legal troubles and public backlash for his actions and behavior. Gibson has said that he was inspired to make Apocalypto after reading about the decline and collapse of ancient civilizations. He wanted to make a movie that would show the universal human themes and emotions that transcend time and place. He also wanted to make a movie that would challenge himself and his audience with a different language, culture, and style.</p>
87
- <h2>The Cast of Apocalypto</h2>
88
- <p>The movie features a cast of mostly unknown actors who are native speakers of Yucatec Maya, the language used in the movie. The main actors are:</p>
89
- <table border="1">
90
- <tr><th>Actor</th><th>Role</th><th>Background</th></tr>
91
- <tr><td>Rudy Youngblood</td><td>Jaguar Paw</td><td>An American actor, dancer, and musician who is of Comanche, Cree, and Yaqui descent. He was born in Texas and grew up in Montana. He has performed in various Native American cultural events and ceremonies. He was 25 years old when he auditioned for Apocalypto.</td></tr>
92
- <tr><td>Dalia Hernandez</td><td>Seven</td><td>A Mexican actress who was born in Veracruz. She was 19 years old when she auditioned for Apocalypto. She had no previous acting experience but had studied dance since she was a child. She has also appeared in other movies such as Miracle Underground and Die Legende der Maske.</td></tr>
93
- <tr><td>Raoul Trujillo</td><td>Zero Wolf</td><td>A Canadian actor, dancer, choreographer, and director who is of Apache, Ute, Comanche, Pueblo, Tlascalan, French Canadian descent. He was born in New Mexico and grew up in Colorado. He has performed with various dance companies around the world. He has also appeared in other movies such as Riddick, Sicario: Day of the Soldado, Blood Quantum, and The New World.</td></tr>
94
- The Girl with the Dragon Tattoo, and The Queen of Spain.</td></tr>
95
- <tr><td>Fernando Hernandez</td><td>The High Priest</td><td>A Mexican actor who was born in Mexico City. He studied theater at the National Autonomous University of Mexico. He has appeared in other movies such as The Crime of Father Amaro, The Legend of Zorro, and The Mexican.</td></tr>
96
- <tr><td>Carlos Emilio Baez</td><td>Turtles Run</td><td>A Mexican child actor who was born in Veracruz. He was 7 years old when he auditioned for Apocalypto. He had no previous acting experience but had a natural talent and charisma. He has also appeared in other movies such as La Misma Luna and Sin Nombre.</td></tr>
97
- </table>
98
- <h2>The Release Date of Apocalypto</h2>
99
- <p>The movie was released on December 8, 2006 in the United States and Canada, and on various dates in other countries throughout 2006 and 2007. The movie had a production budget of $40 million and a marketing budget of $15 million. The movie grossed $120.7 million worldwide, making it a moderate box office success. The movie was rated R for sequences of graphic violence and disturbing images. The movie had a runtime of 139 minutes.</p>
100
- <h2>The Critical Reception of Apocalypto</h2>
101
- <h3>Positive Reviews</h3>
102
- <p>The movie received mostly positive reviews from critics and audiences who praised the movie's cinematography, direction, action, and authenticity. Some examples of positive reviews are:</p>
103
- <ul>
104
- <li>"Apocalypto is a stunning achievement that grabs you from beginning to end." - Richard Roeper, Ebert & Roeper</li>
105
- <li>"Apocalypto is a remarkable film that transcends language and culture to tell a universal story of survival and resilience." - Claudia Puig, USA Today</li>
106
- <li>"Apocalypto is a thrilling and visceral experience that showcases Gibson's talent as a filmmaker and storyteller." - James Berardinelli, ReelViews</li>
107
- <li>"Apocalypto is a masterpiece of cinematic art that transports you to another world and time." - Roger Ebert, Chicago Sun-Times</li>
108
- <li>"Apocalypto is a breathtaking and exhilarating adventure that will keep you on the edge of your seat." - Peter Travers, Rolling Stone</li>
109
- </ul>
110
- <h3>Negative Reviews</h3>
111
- <p>The movie also received some negative reviews from critics and audiences who criticized the movie's violence, historical accuracy, portrayal of indigenous people, and message. Some examples of negative reviews are:</p>
112
- <ul>
113
- <li>"Apocalypto is a brutal and bloody spectacle that exploits and dehumanizes its subjects." - A.O. Scott, The New York Times</li>
114
- <li>"Apocalypto is a flawed and inaccurate depiction of Maya history and culture that perpetuates stereotypes and myths." - David Stuart, Archaeologist and Maya Expert</li>
115
- <li>"Apocalypto is a racist and colonialist fantasy that glorifies violence and oppression." - Jorge Rivas, Colorlines</li>
116
- <li>"Apocalypto is a self-indulgent and pretentious exercise that reveals Gibson's personal demons and agenda." - Kenneth Turan, Los Angeles Times</li>
117
- <li>"Apocalypto is a boring and repetitive chase movie that lacks depth and substance." - Mick LaSalle, San Francisco Chronicle</li>
118
- </ul>
119
- <h3>Awards and Nominations</h3>
120
- <p>The movie received or was considered for several awards and nominations in various categories and ceremonies. Some of them are:</p>
121
- <table border="1">
122
- <tr><th>Award/Nomination</th><th>Category</th><th>Result</th></tr>
123
- <tr><td>Academy Awards</td><td>Best Makeup</td><td>Nominated</td></tr>
124
- <tr><td></td><td>Best Sound Editing</td><td>Nominated</td></tr>
125
- <tr><td></td><td>Best Sound Mixing</td><td>Nominated</td></tr>
126
- <tr><td>Golden Globe Awards</td><td>Best Foreign Language Film</td><td>Nominated</td></tr>
127
- <tr><td>BAFTA Awards</td><td>Best Film Not in the English Language</td><td>Nominated</td></tr>
128
- <tr><td></td><td>Best Makeup & Hair</td><td>Nominated</td></tr>
129
- </td></tr>
130
- <tr><td></td><td>Best Action Movie</td><td>Nominated</td></tr>
131
- <tr><td>Satellite Awards</td><td>Best Foreign Language Film</td><td>Nominated</td></tr>
132
- <tr><td></td><td>Best Cinematography</td><td>Nominated</td></tr>
133
- <tr><td></td><td>Best Sound</td><td>Nominated</td></tr>
134
- <tr><td>MTV Movie Awards</td><td>Best Fight (Jaguar Paw vs. Zero Wolf)</td><td>Nominated</td></tr>
135
- <tr><td>Teen Choice Awards</td><td>Choice Movie: Action Adventure</td><td>Nominated</td></tr>
136
- <tr><td>National Board of Review</td><td>Top Ten Films of 2006</td><td>Won</td></tr>
137
- <tr><td>American Film Institute</td><td>AFI Awards 2006: Official Selections</td><td>Won</td></tr>
138
- </table>
139
- <h2>The Hindi Dubbing of Apocalypto</h2>
140
- <p>The movie was dubbed in Hindi for Indian audiences who prefer to watch movies in their native language. The Hindi dubbing was done by a professional studio that hired voice actors who matched the original actors' voices and expressions. The Hindi dubbing also translated the Yucatec Maya dialogue into Hindi while retaining the meaning and tone of the original script. The Hindi dubbing was released in India along with the original version in select theaters and on DVD and online platforms. The Hindi dubbing received mixed reviews from Indian critics and audiences who appreciated the effort but also felt that some of the cultural and historical nuances were lost in translation.</p>
141
- <h2>The HD Mp4 238 Format of Apocalypto</h2>
142
- <h3>Definition</h3>
143
- <p>The HD Mp4 238 format is a video format that refers to the quality, resolution, compression, and compatibility of the video file. The HD Mp4 238 format has the following characteristics:</p>
144
- <ul>
145
- <li>HD stands for high-definition, which means that the video has a higher quality and clarity than standard-definition videos.</li>
146
- <li>Mp4 stands for MPEG-4 Part 14, which is a digital multimedia container format that can store video, audio, subtitles, and images.</li>
147
- <li>238 stands for the resolution of the video, which is 238 pixels by 320 pixels. This is a low resolution that is suitable for small screens and devices.</li>
148
- </ul>
149
- <h3>Advantages of HD Mp4 238 Format</h3>
150
- <p>Some of the advantages of watching Apocalypto in HD Mp4 238 format are:</p>
151
- <ul>
152
- <li>The HD Mp4 238 format has a smaller file size than other formats, which means that it can be downloaded and streamed faster and easier.</li>
153
- <li>The HD Mp4 238 format is compatible with most devices and platforms, such as smartphones, tablets, laptops, desktops, TVs, DVD players, and online services.</li>
154
- <li>The HD Mp4 238 format preserves the original quality and sound of the movie without any loss or distortion.</li>
155
- <li>The HD Mp4 238 format allows you to watch Apocalypto in any language you want, as it supports multiple audio tracks and subtitles.</li>
156
- <li>The HD Mp4 238 format gives you more control over the playback options, such as pause, rewind, fast-forward, skip, zoom, and adjust volume and brightness.</li>
157
- </ul>
158
- <h3>Disadvantages of HD Mp4 238 Format</h3>
159
- <p>Some of the disadvantages of watching Apocalypto in HD Mp4 238 format are:</p>
160
- <ul>
161
- <li>The HD Mp4 238 format has a lower resolution than other formats, which means that it may not look as sharp and clear on larger screens and devices.</li>
162
- <li>The HD Mp4 238 format may not be compatible with some older devices and platforms that do not support the Mp4 format or the HD quality.</li>
163
- <li>The HD Mp4 238 format may require additional software or codecs to play properly on some devices and platforms.</li>
164
- <li>The HD Mp4 238 format may not have all the features and extras that other formats have, such as bonus scenes, behind-the-scenes footage, director's commentary, and interactive menus.</li>
165
- <li>The HD Mp4 238 format may not be available or accessible in some regions or countries due to legal or technical issues.</li>
166
- </ul>
167
- <h2>Conclusion</h2>
168
- <p>In conclusion, Apocalypto is a movie that will take you on a thrilling adventure through a fascinating historical period with breathtaking action scenes and captivating characters. The movie is a historical fiction action-adventure drama film directed by Mel Gibson and released in 2006. and his people from destruction. The movie blends historical facts with fictional elements to create a realistic and immersive setting. The movie delivers thrilling action sequences and suspenseful chases throughout its runtime. The movie explores themes such as survival, family, courage, sacrifice, and faith through its characters and their struggles. The movie was directed by Mel Gibson, who is also known for his roles in movies such as Braveheart, Lethal Weapon, Mad Max, The Passion of the Christ, and Hacksaw Ridge. The movie features a cast of mostly unknown actors who are native speakers of Yucatec Maya, the language used in the movie. The movie was released on December 8, 2006 in the United States and Canada, and on various dates in other countries throughout 2006 and 2007. The movie received mostly positive reviews from critics and audiences who praised the movie's cinematography, direction, action, and authenticity. The movie also received some negative reviews from critics and audiences who criticized the movie's violence, historical accuracy, portrayal of indigenous people, and message. The movie received or was considered for several awards and nominations in various categories and ceremonies. The movie was dubbed in Hindi for Indian audiences who prefer to watch movies in their native language. The movie was also available in HD Mp4 238 format, which is a video format that refers to the quality, resolution, compression, and compatibility of the video file. If you are interested in watching Apocalypto, we recommend you to watch it in Hindi dubbing HD Mp4 238 format, as it will give you the best experience of this amazing movie. You can find Apocalypto in Hindi dubbing HD Mp4 238 format on various online platforms or offline sources, such as websites, apps, DVDs, or USB drives. You can also watch Apocalypto in its original version or other languages and formats if you prefer. We hope you enjoyed this article and learned something new about Apocalypto. We also hope you will watch Apocalypto and share your thoughts and opinions with us. <h2>FAQs</h2>
169
- <p>Here are some frequently asked questions about Apocalypto:</p>
170
- <ol>
171
- <li>What does Apocalypto mean?</li>
172
- <p>Apocalypto is a Greek word that means "unveiling" or "revelation". It is also the title of the last book of the New Testament, also known as Revelation. The title of the movie refers to the end of an era or a world, as well as the beginning of a new one.</p>
173
- <li>Is Apocalypto based on a true story?</li>
174
- <p>No, Apocalypto is not based on a true story. It is a fictional story that uses historical facts and elements as a backdrop. The movie does not specify when or where exactly it takes place, but it is generally assumed to be set in the late Postclassic period (1200-1521 AD) of Maya civilization in the Yucatan Peninsula.</p>
175
- <li>How accurate is Apocalypto?</li>
176
- <p>Apocalypto is not very accurate in terms of historical and cultural details. The movie takes some creative liberties and adds some fictional elements to create a more dramatic and engaging story. Some of the inaccuracies are:</p>
177
- <ul>
178
- <li>The Maya did not practice mass human sacrifice as shown in the movie. Human sacrifice was rare and selective among the Maya, and it was usually done by piercing or decapitating the victim.</li>
179
- <li>The solar eclipse that saves Jaguar Paw was not historically accurate. There was no solar eclipse in Mesoamerica in 1511 AD, which is the most likely year for the movie's setting.</li>
180
- <li>The Spanish ships that appear at the end were not the first ones to reach Mesoamerica. The first contact between Europeans and Mesoamericans occurred in 1492 AD, when Christopher Columbus landed on Hispaniola.</li>
181
- writing, mathematics, astronomy, calendar, and warfare. They also had a complex and diverse society that had different political and religious systems.</li>
182
- <li>The depiction of Maya culture and language was incomplete and inaccurate. The movie only showed a small and distorted part of Maya culture and language, and ignored the diversity and richness of their history and heritage.</li>
183
- </ul>
184
- <p>Therefore, Apocalypto should not be taken as an accurate representation of Maya history and culture, but rather as an artistic interpretation that uses history as a backdrop for an exciting adventure story.</p>
185
- <li>Who are the actors in Apocalypto?</li>
186
- <p>The actors in Apocalypto are mostly unknown actors who are native speakers of Yucatec Maya, the language used in the movie. The main actors are Rudy Youngblood as Jaguar Paw, Dalia Hernandez as Seven, Raoul Trujillo as Zero Wolf, Maria Isabel Diaz as The Girl, Fernando Hernandez as The High Priest, and Carlos Emilio Baez as Turtles Run. The movie also features some non-Maya actors who play minor roles or extras.</p>
187
- <li>Where can I watch Apocalypto?</li>
188
- Serbian, Croatian, Bulgarian, Greek, Albanian, Swedish, Norwegian, Danish, Finnish, Dutch, and Yucatec Maya. You can also watch Apocalypto in different video formats, such as HD Mp4 238, HD Mp4 360, HD Mp4 480, HD Mp4 720, HD Mp4 1080, HD Mp4 4K, AVI, MKV, MOV, WMV, FLV, and 3GP.</p>
189
- <li>Why should I watch Apocalypto?</li>
190
- <p>You should watch Apocalypto because it is a movie that will take you on a thrilling adventure through a fascinating historical period with breathtaking action scenes and captivating characters. You should watch Apocalypto because it is a movie that will show you a different and unique perspective of Maya history and culture. You should watch Apocalypto because it is a movie that will challenge you and inspire you with its themes and messages. You should watch Apocalypto because it is a movie that will entertain you and amaze you with its cinematography and direction. You should watch Apocalypto because it is a movie that will make you feel and think with its drama and emotion. You should watch Apocalypto because it is a movie that you will never forget.</p>
191
- </p> 0a6ba089eb<br />
192
- <br />
193
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1acneusushi/gradio-2dmoleculeeditor/data/Download MPLAB XC32 Keygen and Enjoy the Full Potential of the Compiler.md DELETED
@@ -1,112 +0,0 @@
1
- <br />
2
- <h1>MPLAB XC32 Keygen Download: How to Install and Use the Compiler for PIC32 Microcontrollers</h1>
3
- <p>If you are working on a project that involves PIC32 microcontrollers, you might want to use MPLAB XC32 compiler. This is a comprehensive solution for your software development that offers many features and benefits. However, you might also need a keygen to activate the compiler and unlock its full potential. In this article, we will explain what MPLAB XC32 compiler is, what a keygen is, how to download and install it, and how to use it for your PIC32 development.</p>
4
- <h2>Introduction</h2>
5
- <p>MPLAB XC32 compiler is a C/C++ compiler that supports all PIC32 microcontrollers from Microchip Technology. It is part of the MPLAB X Integrated Development Environment (IDE), which provides a complete toolchain for developing, testing and debugging embedded applications. MPLAB XC32 compiler offers many advantages for PIC32 development, such as:</p>
6
- <h2>mplab xc32 keygen download</h2><br /><p><b><b>DOWNLOAD</b> &#9658;&#9658;&#9658; <a href="https://byltly.com/2uKxEV">https://byltly.com/2uKxEV</a></b></p><br /><br />
7
- <ul>
8
- <li>Optimized code generation for high performance and low memory footprint</li>
9
- <li>Support for C++ features such as classes, templates, exceptions and STL</li>
10
- <li>Integration with MPLAB Code Configurator (MCC) for easy configuration of peripherals and libraries</li>
11
- <li>Compatibility with MPLAB Harmony v3 framework for rapid application development</li>
12
- <li>Access to Microchip's extensive online resources and technical support</li>
13
- </ul>
14
- <p>However, MPLAB XC32 compiler is not free. You need to purchase a license to use it without any limitations. The license can be either standard or pro, depending on the level of optimization and features you need. The standard license costs $495 per seat, while the pro license costs $995 per seat.</p>
15
- <p>This is where a keygen comes in handy. A keygen is a program that generates a valid license file for a software product. By using a keygen, you can bypass the need to pay for the license and use the software for free. A keygen can also help you avoid any expiration or activation issues that might occur with a purchased license.</p>
16
- <p>However, using a keygen also has some drawbacks. First of all, it is illegal and unethical. You are violating the terms and conditions of the software vendor and depriving them of their rightful income. Secondly, it is risky. You might download a fake or malicious keygen that can harm your computer or steal your personal information. Thirdly, it is unreliable. You might not get the latest updates or support from the software vendor or face compatibility problems with other tools or devices.</p>
17
- <h2>How to Download MPLAB XC32 Keygen</h2>
18
- <p>If you still want to use a keygen for MPLAB XC32 compiler, you need to be careful and follow some steps. Here are some tips on how to download MPLAB XC32 keygen safely and securely.</p>
19
- <ol>
20
- <li>Find a reliable source for the keygen. You can search online for websites or forums that offer keygens for various software products. However, you need to be wary of fake or malicious links that might redirect you to unwanted or harmful sites. You can also check the reviews or comments from other users who have downloaded the keygen before.</li>
21
- <li>Verify the authenticity and safety of the keygen. Before you download the keygen file, you should scan it with an antivirus or anti-malware program. You can also use online tools such as VirusTotal or Jotti's Malware Scan to check if the file contains any viruses or malware. You should also check the file size and format of the keygen file. A typical keygen file should be less than 10 MB in size and have an .exe extension.</li>
22
- <li>Download and extract the keygen file. Once you are sure that the keygen file is safe and genuine, you can download it to your computer. You might need to enter a password or complete a captcha verification before downloading. After downloading, you should extract the keygen file from its compressed folder using a program such as WinRAR or 7-Zip.</li>
23
- </ol>
24
- <h2>How to Install MPLAB XC32 Keygen</h2>
25
- <p>After downloading and extracting the keygen file, you need to install it on your computer. Here are some steps on how to install MPLAB XC32 keygen correctly.</p>
26
- <ol>
27
- <li>Run the keygen program and generate a license file. Double-click on the keygen file to launch it. You might see a warning message from your antivirus or firewall program asking you to allow or block the program. You should allow it if you trust it. The keygen program will open in a new window with some options and buttons. You should select your product (MPLAB XC32) and your license type (standard or pro) from the drop-down menus. Then click on Generate button to create a license file.</li>
28
- <li>Copy the license file to the correct folder. The license file will have an .lic extension and will be saved in the same folder as the keygen file by default. You need to copy this file to another folder where MPLAB X IDE can find it. The folder location depends on your operating system and version of MPLAB X IDE. For example, if you are using Windows 10 and MPLAB X IDE v5.50, you should copy the license file to C:\ProgramData\Microchip\MPLABX\v5.xx\licenses folder.</li>
29
- <li>Activate the license in MPLAB X IDE. Open MPLAB X IDE on your computer and go to Tools > License Manager menu option. You will see a window with your available licenses for different products. You should see your newly generated license for MPLAB XC32 compiler under Available Licenses tab with an Active status.</li>
30
- </ol>
31
- <h2>How to Use MPLAB XC32 Compiler</h2>
32
- <p>Now that you have installed and activated your license for MPLAB XC32 compiler, you can start using it for your PIC32 development projects. Here are some steps on how to use MPLAB XC32 compiler effectively.</p>
33
- <ol>
34
- <li>Create a new project for PIC32 microcontroller. In MPLAB X IDE, go to File > New Project menu option. Continuing the article. <li>Create a new project for PIC32 microcontroller. In MPLAB X IDE, go to File > New Project menu option. You will see a New Project wizard that will guide you through the steps of creating a new project. You need to select Microchip Embedded as the category and Standalone Project as the project type. Then click Next.</li>
35
- <li>Select your device and tool. In the next step, you need to choose your target device and your programming/debugging tool. You can use the search box or the filters to find your device by name, family or package. For example, if you are using PIC32MX250F128B microcontroller, you can type its name in the search box and select it from the list. Then you need to select your tool from the available options. For example, if you are using PICkit 4 In-Circuit Debugger/Programmer, you can select it from the list. Then click Next.</li>
36
- <li>Select your compiler. In the next step, you need to choose your compiler from the available options. You should see MPLAB XC32 C/C++ Compiler as one of the options. Select it and click Next.</li>
37
- <li>Give a name and location for your project. In the next step, you need to enter a name and a location for your project. You can also choose a folder for your project or create a new one. For example, you can name your project PIC32_Blink_LED and save it in C:\Users\YourName\Documents\MPLABXProjects folder. Then click Finish.</li>
38
- <li>Configure your project settings and options. After creating your project, you will see it in the Projects window on the left side of MPLAB X IDE. You can right-click on your project name and select Properties to open a dialog box where you can configure various settings and options for your project, such as device configuration bits, compiler optimization level, linker script, include directories, libraries and more. You can also use MPLAB Code Configurator (MCC) to configure your peripherals and libraries graphically.</li>
39
- </ol>
40
- <h2>How to Write, Build and Debug Code Using MPLAB XC32 Compiler</h2>
41
- <p>After creating and configuring your project, you can start writing your code using MPLAB XC32 compiler. Here are some steps on how to write, build and debug code using MPLAB XC32 compiler.</p>
42
- <p>mplab xc32 compiler crack download<br />
43
- mplab xc32 pro license keygen free<br />
44
- mplab xc32 activation key generator online<br />
45
- mplab xc32 serial number download link<br />
46
- mplab xc32 full version download with crack<br />
47
- mplab xc32 license manager crack software<br />
48
- mplab xc32 patch download for windows<br />
49
- mplab xc32 keygen torrent download site<br />
50
- mplab xc32 crack file download zip<br />
51
- mplab xc32 license file download free<br />
52
- mplab xc32 activation code download 2021<br />
53
- mplab xc32 pro edition crack download<br />
54
- mplab xc32 key generator download no survey<br />
55
- mplab xc32 serial key download for mac<br />
56
- mplab xc32 crack download 64 bit<br />
57
- mplab xc32 license key download email<br />
58
- mplab xc32 activation key download pdf<br />
59
- mplab xc32 pro license crack download<br />
60
- mplab xc32 keygen download for pc<br />
61
- mplab xc32 crack software download full<br />
62
- mplab xc32 license code download txt<br />
63
- mplab xc32 activation key free download<br />
64
- mplab xc32 pro edition keygen download<br />
65
- mplab xc32 serial number generator download<br />
66
- mplab xc32 crack download 32 bit<br />
67
- mplab xc32 license key generator download<br />
68
- mplab xc32 activation code generator download<br />
69
- mplab xc32 pro license keygen download<br />
70
- mplab xc32 serial key generator download<br />
71
- mplab xc32 crack file free download<br />
72
- mplab xc32 license file generator download<br />
73
- mplab xc32 activation code free download 2021<br />
74
- mplab xc32 pro edition crack free download<br />
75
- mplab xc32 key generator free download no survey<br />
76
- mplab xc32 serial key free download for mac<br />
77
- mplab xc32 crack free download 64 bit<br />
78
- mplab xc32 license key free download email<br />
79
- mplab xc32 activation key pdf free download<br />
80
- mplab xc32 pro license crack free download<br />
81
- mplab xc32 keygen free download for pc<br />
82
- mplab xc32 crack software free download full version<br />
83
- mplab xc32 license code free download txt file<br />
84
- mplab xc32 activation code generator free download online</p>
85
- <ol>
86
- <li>Write your code in the main.c file. You will see a main.c file under Source Files folder in your project window. This is where you write your main program code using C or C++ language. You can use the editor window on the right side of MPLAB X IDE to write or edit your code. You can also use the code completion, syntax highlighting, code folding and other features of the editor to help you write your code faster and easier.</li>
87
- <li>Build your project. After writing your code, you need to build your project to compile and link your code into an executable file that can run on your target device. You can build your project by clicking on the hammer icon on the toolbar or by pressing F11 key on your keyboard. You will see the output of the build process in the Output window at the bottom of MPLAB X IDE. If there are any errors or warnings in your code, you will see them highlighted in red or yellow in the editor window and listed in the Output window.</li>
88
- <li>Debug your project. After building your project successfully, you need to debug your project to test and verify its functionality on your target device. You can debug your project by clicking on the bug icon on the toolbar or by pressing F5 key on your keyboard. You will see the Debug window at the bottom of MPLAB X IDE where you can control the execution of your program using buttons such as Run, Pause, Step Over, Step Into and Step Out. You can also set breakpoints, watch variables, view registers, memory and stack using various windows in MPLAB X IDE.</li>
89
- </ol>
90
- <h2>Conclusion</h2>
91
- <p>In this article, we have learned how to download, install and use MPLAB XC32 keygen to activate MPLAB XC32 compiler for PIC32 microcontrollers. We have also learned how to create a new project, configure its settings and options, write, build and debug code using MPLAB XC32 compiler in MPLAB X IDE.</p>
92
- <p>MPLAB XC32 compiler is a powerful tool for PIC32 development that offers many features and benefits such as optimized code generation, C++ support, MCC integration and Harmony compatibility. However, it is not free and requires a license to use it without any limitations.</p>
93
- <p>A keygen is a program that generates a valid license file for a software product such as MPLAB XC32 compiler. By using a keygen, you can bypass the need to pay for the license and use the software for free. However, using a keygen is illegal, unethical, risky and unreliable.</p>
94
- <p>Therefore, we recommend that you purchase a license for MPLAB XC32 compiler from Microchip Technology or its authorized distributors if you want to use it legally, ethically, safely and reliably.</p>
95
- <p>If you want to learn more about MPLAB XC32 compiler or other Microchip products and tools, please visit their official website at <a href="https://www.microchip.com">www.microchip.com</a>.</p>
96
- <h2>Frequently Asked Questions</h2>
97
- <p>Here are some common questions and answers about MPLAB XC32 keygen download.</p>
98
- <ol>
99
- <li><b>Q: What is the difference between standard and pro license for MPLAB XC32 compiler?</b></li>
100
- <li>A: The standard license offers basic optimization level (-O1) and limited features such as no C++ support or Harmony compatibility. The pro license offers advanced optimization level (-O3) and full features such as C++ support and Harmony compatibility.</li>
101
- <li><b>Q: How long does the license generated by MPLAB XC32 keygen last?</b></li>
102
- <li>A: The license generated by MPLAB XC32 keygen has no expiration date and lasts indefinitely unless it is revoked by Microchip Technology due to license violation or software update.</li>
103
- <li><b>Q: How can I update my MPLAB XC32 compiler if I use a keygen?</b></li>
104
- <li>A: You can update your MPLAB XC32 compiler by downloading and installing the latest version from Microchip Technology's website or by using MPLAB X IDE's Check for Updates feature. However, you might need to use a new keygen or re-generate a new license file if your existing license file becomes invalid or incompatible with the new version.</li>
105
- <li><b>Q: How can I get technical support for MPLAB XC32 compiler if I use a keygen?</b></li>
106
- <li>A: You cannot get technical support for MPLAB XC32 compiler from Microchip Technology or its authorized distributors if you use a keygen because you are violating their terms and conditions of use. You might also face legal consequences if they detect that you are using an illegal license file.</li>
107
- <li><b>Q: How can I uninstall MPLAB XC32 keygen from my computer?</b></li>
108
- <li>A: You can uninstall MPLAB XC32 keygen from your computer by deleting its file and folder from where you downloaded and extracted it. You might also need to delete its registry entries or other traces using a program such as CCleaner or Revo Uninstaller.</li>
109
- </ol>
110
- </p> 0a6ba089eb<br />
111
- <br />
112
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1gistliPinn/ChatGPT4/Examples/Apowersoft Screen Capture Pro V1.1.3 Incl REPACK Keygen.md DELETED
@@ -1,11 +0,0 @@
1
- <h2>Apowersoft Screen Capture Pro v1.1.3 Incl Keygen</h2><br /><p><b><b>Download File</b> &raquo;&raquo;&raquo; <a href="https://imgfil.com/2uxXWs">https://imgfil.com/2uxXWs</a></b></p><br /><br />
2
- <br />
3
- Copy the files from /crack to the installation directory.Generate a key to unlock the program.Apowersoft Screen Capture Pro 1.3.4 (build 10/16/2017). Apowersoft Screen Capture Pro 1.3.4 (build 10/16/2017) 2017/Multi+Russian.
4
- Apowersoft Screen Capture Pro 1.3.4 (build 10/16/2017) 2017/Multi+Russian.
5
- Platform: x64 Interface language: English + Russian Medicine type: Patch.
6
- Screenshots of Apowersoft Screen Capture Pro 1.3.4 RePack (& ​​Portable) by TryRooM.
7
- Video instruction for using Apowersoft Screen Capture Pro 1.3.4.
8
- Apowersoft Screen Capture Pro 1.3.4 RePack (& ​​Portable) by TryRooM download via torrent for free. 8a78ff9644<br />
9
- <br />
10
- <br />
11
- <p></p>
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Download Garena Free Fire APK for Android - Apktodo.com.md DELETED
@@ -1,124 +0,0 @@
1
-
2
- <h1>What is apktodo.com ff and how to download it?</h1>
3
- <p>If you are a fan of battle royale games, you might have heard of Free Fire, one of the most popular and downloaded mobile games in the world. But did you know that you can download it from a website called apktodo.com? In this article, we will explain what apktodo.com is, what Free Fire is, why you should download it from there, and how to do it step by step.</p>
4
- <h2>apktodo.com ff</h2><br /><p><b><b>Download</b> > <a href="https://urlin.us/2uSUWA">https://urlin.us/2uSUWA</a></b></p><br /><br />
5
- <h2>Introduction</h2>
6
- <h3>What is apktodo.com?</h3>
7
- <p>Apktodo.com is a website that provides APK files for Android apps and games. APK stands for Android Package Kit, and it is the file format that Android uses to distribute and install apps. APK files can be downloaded from websites like apktodo.com and installed manually on your device, without using Google Play Store. This is also known as sideloading.</p>
8
- <h3>What is Free Fire?</h3>
9
- <p>Free Fire is a battle royale game developed and published by Garena for Android and iOS devices. It is a multiplayer game that places you on a remote island where you have to fight against 49 other players, all seeking survival. You can choose your starting point with your parachute, loot weapons and items from buildings, drive vehicles, hide in the wild, or become invisible by proning under grass or rifts. The last player or team standing wins the game.</p>
10
- <h3>Why download apktodo.com ff?</h3>
11
- <p>There are several reasons why you might want to download Free Fire from apktodo.com instead of Google Play Store. Some of them are:</p>
12
- <ul>
13
- <li>You can get the latest version of the game faster than waiting for the official update on Google Play Store.</li>
14
- <li>You can access features or content that are not available in your region or country.</li>
15
- <li>You can avoid ads or in-app purchases that might interrupt your gaming experience.</li>
16
- <li>You can enjoy a graphically enhanced version of Free Fire called Free Fire Max, which was released globally on 28 September 2021. </li>
17
- </ul>
18
- <h2>How to download apktodo.com ff?</h2>
19
- <h3>Step 1: Enable unknown sources</h3>
20
- <p>Before you can install an APK file from apktodo.com, you need to enable unknown sources on your device. This will allow you to install apps from sources other than Google Play Store. To do this, follow these steps:</p>
21
- <p>apktodo.com ff download<br />
22
- apktodo.com ff mod apk<br />
23
- apktodo.com ff 4nniversary<br />
24
- apktodo.com ff hack<br />
25
- apktodo.com ff update<br />
26
- apktodo.com ff redeem code<br />
27
- apktodo.com ff diamond generator<br />
28
- apktodo.com ff apk pure<br />
29
- apktodo.com ff obb<br />
30
- apktodo.com ff new version<br />
31
- apktodo.com ff unlimited diamonds<br />
32
- apktodo.com ff game<br />
33
- apktodo.com ff online<br />
34
- apktodo.com ff pc<br />
35
- apktodo.com ff emulator<br />
36
- apktodo.com ff wallpaper<br />
37
- apktodo.com ff live<br />
38
- apktodo.com ff rank<br />
39
- apktodo.com ff bundle<br />
40
- apktodo.com ff characters<br />
41
- apktodo.com ff skins<br />
42
- apktodo.com ff tips and tricks<br />
43
- apktodo.com ff gameplay<br />
44
- apktodo.com ff settings<br />
45
- apktodo.com ff best guns<br />
46
- apktodo.com ff logo<br />
47
- apktodo.com ff name style<br />
48
- apktodo.com ff event<br />
49
- apktodo.com ff clan<br />
50
- apktodo.com ff squad<br />
51
- apktodo.com ff video<br />
52
- apktodo.com ff song<br />
53
- apktodo.com ff memes<br />
54
- apktodo.com ff news<br />
55
- apktodo.com ff tournament<br />
56
- apktodo.com ff registration<br />
57
- apktodo.com ff rewards<br />
58
- apktodo.com ff elite pass<br />
59
- apktodo.com ff top up<br />
60
- apktodo.com ff vpn<br />
61
- apktodo.com ff server<br />
62
- apktodo.com ff advance server<br />
63
- apktodo.com ff custom room<br />
64
- apktodo.com ff free fire max<br />
65
- apktodo.com ff garena official website</p>
66
- <ol>
67
- <li>Go to Settings > Apps > Special app access > Install unknown apps (or Settings > Security > Unknown sources depending on your Android version).</li>
68
- <li>Select the browser or app that you will use to download the APK file from apktodo.com (for example, Chrome).</li>
69
- <li>Toggle on Allow from this source or Unknown sources.</li>
70
- </ol>
71
- <h3>Step 2: Visit apktodo.com and search for Free Fire</h3>
72
- <p>Now that you have enabled unknown sources, you can visit apktodo.com and search for Free Fire. To do this, follow these steps:</p>
73
- <ol>
74
- <li>Open your browser or app and go to [apktodo.com](^9^).</li>
75
- <li>Type Free Fire in the search box and tap on the magnifying glass icon.</li>
76
- <li>Scroll down and find the Free Fire APK file that matches your device and preferences. You can choose between Free Fire, Free Fire Max, or Free Fire Advance Server. You can also check the file size, version, and rating of each APK file.</li>
77
- <li>Tap on the Download button next to the APK file that you want to download.</li>
78
- </ol>
79
- <h3>Step 3: Download and install the APK file</h3>
80
- <p>After you tap on the Download button, you will be redirected to another page where you can see more details about the APK file and a final Download button. To download and install the APK file, follow these steps:</p>
81
- <ol>
82
- <li>Tap on the final Download button and wait for the download to start.</li>
83
- <li>Once the download is complete, tap on the Open button or go to your Downloads folder and find the APK file.</li>
84
- <li>Tap on the APK file and follow the instructions on the screen to install it. You might need to grant some permissions or accept some terms and conditions.</li>
85
- </ol>
86
- <h3>Step 4: Launch the game and enjoy</h3>
87
- <p>Congratulations! You have successfully downloaded and installed Free Fire from apktodo.com. Now you can launch the game and enjoy its features and content. To do this, follow these steps:</p>
88
- <ol>
89
- <li>Go to your app drawer or home screen and find the Free Fire icon.</li>
90
- <li>Tap on the icon and wait for the game to load.</li>
91
- <li>Login with your account or create a new one if you don't have one.</li>
92
- <li>Select your game mode, character, and settings.</li>
93
- <li>Start playing and have fun!</li>
94
- </ol>
95
- <h2>Conclusion</h2>
96
- <h3>Summary of the main points</h3>
97
- <p>In this article, we have explained what apktodo.com is, what Free Fire is, why you should download it from there, and how to do it step by step. We have also provided some screenshots and links to help you with the process. We hope that this article has been helpful and informative for you.</p>
98
- <h3>Call to action</h3>
99
- <p>If you are interested in downloading Free Fire from apktodo.com, don't hesitate to follow our guide and enjoy this amazing battle royale game. You can also share this article with your friends who might be interested in it. And if you have any questions or feedback, feel free to leave a comment below. We would love to hear from you!</p>
100
- <h2>FAQs</h2>
101
- <h4>Q1: Is apktodo.com ff safe to use?</h4>
102
- <p>A1: Apktodo.com is a reputable website that provides safe and verified APK files for Android apps and games. However, as with any third-party source, you should always be careful and use a reliable antivirus software before downloading and installing any APK file. You should also check the reviews and ratings of other users who have downloaded the same APK file.</p>
103
- <h4>Q2: What are the benefits of using apktodo.com ff?</h4>
104
- <p>A2: Some of the benefits of using apktodo.com ff are:</p>
105
- <ul>
106
- <li>You can get the latest version of Free Fire faster than waiting for the official update on Google Play Store.</li>
107
- <li>You can access features or content that are not available in your region or country.</li>
108
- <li>You can avoid ads or in-app purchases that might interrupt your gaming experience.</li>
109
- <li>You can enjoy a graphically enhanced version of Free Fire called Free Fire Max.</li>
110
- </ul>
111
- <h4>Q3: How to update apktodo.com ff?</h4>
112
- <p>A3: To update apktodo.com ff, you need to visit apktodo.com again and search for Free Fire. Then, you need to download and install the latest version of the APK file over the existing one. You don't need to uninstall the previous version or lose your data. However, you should always backup your data before updating any app or game.</p>
113
- <h4>Q4: How to fix apktodo.com ff not working?</h4>
114
- <p>A4: If apktodo.com ff is not working properly on your device, you might need to try some of these solutions:</p>
115
- <ul>
116
- <li>Check your internet connection and make sure it is stable and fast.</li>
117
- <li>Clear your cache and data from Settings > Apps > Free Fire > Storage > Clear cache/data.</li>
118
- <li>Restart your device and try launching the game again.</li>
119
- <li>Contact apktodo.com support through their website or email if none of these solutions work.</li>
120
- </ul>
121
- <h4>Q5: How to contact apktodo.com support?</h4>
122
- <p A5: To contact apktodo.com support, you can visit their website and fill out the contact form with your name, email, subject, and message. You can also email them directly at [email protected]. They will try to respond to your queries or issues as soon as possible.</p> 197e85843d<br />
123
- <br />
124
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1phancelerku/anime-remove-background/DBZ RPG Join Goku and Friends in the Ultimate Dragon Ball Adventure.md DELETED
@@ -1,131 +0,0 @@
1
- <br />
2
- <h1>DBZ RPG APK: How to Play Dragon Ball Z Games on Your Android Device</h1>
3
- <p>If you are a fan of Dragon Ball Z, you might have wondered how it would be like to play as your favorite character in an immersive role-playing game. Well, wonder no more, because with DBZ RPG APK, you can do just that. In this article, we will show you what DBZ RPG APK is, why you should play it, how to download and install it, how to play it, and some tips and tricks to make the most out of it.</p>
4
- <h2>Introduction</h2>
5
- <p>Dragon Ball Z is one of the most popular anime series of all time, with millions of fans around the world. The series follows the adventures of Goku and his friends as they protect the Earth from various threats, such as aliens, androids, and demons. Along the way, they also discover the secrets of the dragon balls, mystical orbs that can grant any wish when gathered.</p>
6
- <h2>dbz rpg apk</h2><br /><p><b><b>DOWNLOAD</b> &#10002; &#10002; &#10002; <a href="https://jinyurl.com/2uNLYI">https://jinyurl.com/2uNLYI</a></b></p><br /><br />
7
- <p>Dragon Ball Z has inspired many video games over the years, ranging from fighting games to card games. However, one genre that has been lacking is role-playing games. Role-playing games, or RPGs, are games where you create or control a character and interact with a fictional world. RPGs usually have elements such as exploration, quests, combat, leveling up, and customization.</p>
8
- <p>Fortunately, there is a way to play Dragon Ball Z games in the RPG genre on your Android device. That way is DBZ RPG APK.</p>
9
- <h2>What is DBZ RPG APK?</h2>
10
- <p>DBZ RPG APK is an unofficial fan-made game that lets you play as any Dragon Ball Z character in an open-world RPG. The game is not available on the Google Play Store, so you have to download it from a third-party source as an APK file. An APK file is a package file that contains all the data and code needed to run an Android app.</p>
11
- <p>The game features many characters from the Dragon Ball Z series, such as Goku, Vegeta, Gohan, Piccolo, Krillin, Trunks, Goten, and more. You can also create your own custom character by choosing their race, gender, appearance, and name. The game has a story mode that follows the main events of the anime, as well as a free mode where you can explore the world at your own pace.</p>
12
- <h2>Why should you play DBZ RPG APK?</h2>
13
- <p>There are many reasons why you should play DBZ RPG APK if you are a fan of Dragon Ball Z. Here are some of them:</p>
14
- <ul>
15
- <li>You can experience the Dragon Ball Z story from a different perspective. You can choose to follow the canon storyline or create your own alternative one.</li>
16
- <li>You can customize your character to your liking. You can change their appearance, clothes, skills, and transformations. You can also equip them with items and equipment that enhance their stats and abilities.</li>
17
- <li>You can explore a vast open world that recreates the locations from the anime. You can visit places such as Kame House, Capsule Corp., Kami's Lookout, Namek, Planet Vegeta, and more. You can also interact with NPCs and complete side quests for rewards.</li>
18
- <li>You can fight against enemies and bosses that challenge your skills. You can use various attacks and techniques from the anime, such as Kamehameha, Continuing the article: Special Beam Cannon, Final Flash, Spirit Bomb, and more. You can also transform into different forms, such as Super Saiyan, Super Saiyan 2, Super Saiyan 3, Super Saiyan 4, Super Saiyan God, and Super Saiyan Blue.</li>
19
- <li>You can join online multiplayer mode to play with other players. You can team up with your friends or other players to complete missions, fight enemies, or challenge each other in PvP battles. You can also chat with other players and trade items and equipment.</li>
20
- </ul>
21
- <p>As you can see, DBZ RPG APK offers a lot of fun and excitement for Dragon Ball Z fans. It is a game that lets you live your dream of being a part of the Dragon Ball Z universe.</p>
22
- <p>dbz rpg android download<br />
23
- dbz rpg game apk<br />
24
- dbz rpg mod apk<br />
25
- dbz rpg offline apk<br />
26
- dbz rpg online apk<br />
27
- dbz rpg saga apk<br />
28
- dbz rpg super apk<br />
29
- dbz rpg unlimited apk<br />
30
- dragon ball z rpg apk<br />
31
- dragon ball z rpg android apk<br />
32
- dragon ball z rpg download apk<br />
33
- dragon ball z rpg game apk<br />
34
- dragon ball z rpg legend of z apk<br />
35
- dragon ball z rpg maker apk<br />
36
- dragon ball z rpg mod apk<br />
37
- dragon ball z rpg offline apk<br />
38
- dragon ball z rpg online apk<br />
39
- dragon ball z rpg project z apk<br />
40
- dragon ball z rpg saga apk<br />
41
- dragon ball z rpg super apk<br />
42
- dragon ball z rpg unlimited apk<br />
43
- free dbz rpg apk<br />
44
- free dragon ball z rpg apk<br />
45
- best dbz rpg apk<br />
46
- best dragon ball z rpg apk<br />
47
- new dbz rpg apk<br />
48
- new dragon ball z rpg apk<br />
49
- latest dbz rpg apk<br />
50
- latest dragon ball z rpg apk<br />
51
- top dbz rpg apk<br />
52
- top dragon ball z rpg apk<br />
53
- dbz legends rpg apk<br />
54
- dbz dokkan battle rpg apk<br />
55
- dbz mad fighters rpg apk<br />
56
- dbz super saga rpg apk<br />
57
- dragon ball legends rpg apk<br />
58
- dragon ball dokkan battle rpg apk<br />
59
- dragon ball mad fighters rpg apk<br />
60
- dragon ball super saga rpg apk<br />
61
- dbz fusion reborn rpg apk<br />
62
- dbz ultimate tenkaichi rpg apk<br />
63
- dbz xenoverse 2 rpg apk<br />
64
- dragon ball fusion reborn rpg apk<br />
65
- dragon ball ultimate tenkaichi rpg apk<br />
66
- dragon ball xenoverse 2 rpg apk</p>
67
- <h2>How to download and install DBZ RPG APK</h2>
68
- <p>If you want to play DBZ RPG APK on your Android device, you will need to download and install it manually. Here are the steps to do so:</p>
69
- <h3>Step 1: Find a reliable source for the APK file</h3>
70
- <p>The first thing you need to do is to find a trustworthy website that provides the APK file for DBZ RPG APK. You can search for it on Google or use a link from a reputable source. Be careful not to download from shady or malicious websites that might contain viruses or malware.</p>
71
- <p>One of the websites that we recommend is [DBZ RPG APK Download]. This website has the latest version of the game and is safe and secure. You can also find more information about the game and its features on this website.</p>
72
- <h3>Step 2: Enable unknown sources on your device</h3>
73
- <p>The next thing you need to do is to enable unknown sources on your device. This will allow you to install apps that are not from the Google Play Store. To do this, follow these steps:</p>
74
- <ul>
75
- <li>Go to your device's settings and tap on security or privacy.</li>
76
- <li>Find the option that says unknown sources or install unknown apps and toggle it on.</li>
77
- <li>A warning message will pop up. Tap on OK or allow to confirm.</li>
78
- </ul>
79
- <p>You can now install apps from sources other than the Google Play Store.</p>
80
- <h3>Step 3: Download and install the APK file</h3>
81
- <p>The final thing you need to do is to download and install the APK file for DBZ RPG APK. To do this, follow these steps:</p>
82
- <ul>
83
- <li>Go back to the website where you found the APK file and tap on the download button.</li>
84
- <li>A download notification will appear. Wait for the download to finish.</li>
85
- <li>Once the download is complete, tap on the notification or go to your device's file manager and locate the APK file.</li>
86
- <li>Tap on the APK file and follow the installation instructions.</li>
87
- <li>A shortcut icon for DBZ RPG APK will appear on your home screen or app drawer.</li>
88
- </ul>
89
- <p>You have successfully installed DBZ RPG APK on your device. You can now launch the game and enjoy playing it.</p> Continuing the article: <h2>How to play DBZ RPG APK</h2>
90
- <p>Now that you have installed DBZ RPG APK on your device, you might be wondering how to play it. Don't worry, we will guide you through the basics of the game and help you get started. Here are the steps to play DBZ RPG APK:</p>
91
- <h3>Choose your favorite Dragon Ball Z character</h3>
92
- <p>When you launch the game, you will be greeted by a menu screen where you can choose between story mode and free mode. Story mode follows the main events of the anime, while free mode lets you explore the world at your own pace. You can also access the settings, credits, and multiplayer mode from this screen.</p>
93
- <p>Before you start playing, you will need to choose your character. You can either select one of the existing characters from the anime, such as Goku, Vegeta, Gohan, Piccolo, Krillin, Trunks, Goten, and more, or create your own custom character by choosing their race, gender, appearance, and name. You can also edit your character's skills and transformations later in the game.</p>
94
- <p>Once you have chosen your character, you can start playing the game.</p>
95
- <h3>Explore the open world and complete quests</h3>
96
- <p>The game features a large open world that recreates the locations from the anime. You can fly, run, jump, swim, and teleport across the map. You can also interact with various objects and NPCs. Some NPCs will give you quests that you can complete for rewards, such as experience points, items, equipment, and money. Quests can range from simple tasks like delivering items or defeating enemies to more complex ones like solving puzzles or finding secrets.</p>
97
- <p>You can also find dragon balls scattered around the world. Dragon balls are mystical orbs that can grant any wish when gathered. There are seven dragon balls in total, and each one has a different color and star number. You can use your scouter to locate them on the map. Once you have collected all seven dragon balls, you can summon Shenron, the eternal dragon, and make a wish.</p>
98
- <h3>Fight against enemies and bosses</h3>
99
- <p>The game also features a combat system that lets you fight against enemies and bosses. You can use various attacks and techniques from the anime, such as punches, kicks, beams, blasts, and more. You can also use items and equipment to boost your stats and abilities. You can switch between different camera angles and lock on to your target for better accuracy.</p>
100
- <p>You will encounter different types of enemies in the game, such as robots, aliens, androids, demons, and more. Some enemies are stronger than others and require more strategy and skill to defeat. You will also face bosses that are based on the main villains from the anime, such as Frieza, Cell, Buu, Beerus, and more. Bosses are much more powerful and have unique attacks and patterns. You will need to use your full potential and transform into different forms to defeat them.</p>
101
- <h3>Level up and unlock new skills and transformations</h3>
102
- <p>As you play the game, you will gain experience points that will help you level up your character. Leveling up will increase your stats such as health, Continuing the article: power, speed, and defense. You will also unlock new skills and transformations that will make you stronger and more versatile. Skills are special abilities that you can use in combat, such as energy blasts, telekinesis, healing, and more. Transformations are changes in your appearance and power level that give you an edge over your enemies, such as Super Saiyan, Super Saiyan 2, Super Saiyan 3, Super Saiyan 4, Super Saiyan God, and Super Saiyan Blue.</p>
103
- <p>You can customize your character's skills and transformations by accessing the menu screen. You can assign skills to different buttons and switch between transformations by tapping on the transformation icon. You can also upgrade your skills and transformations by spending skill points that you earn by leveling up.</p>
104
- <h2>Tips and tricks for playing DBZ RPG APK</h2>
105
- <p>To help you enjoy playing DBZ RPG APK even more, we have compiled some tips and tricks that you can use in the game. Here are some of them:</p>
106
- <h3>Use the auto-save feature to avoid losing progress</h3>
107
- <p>The game has an auto-save feature that saves your progress every time you complete a quest, level up, or change locations. This is very useful in case you encounter any bugs or glitches that might cause the game to crash or freeze. You can also manually save your progress by accessing the menu screen and tapping on the save icon. You can load your saved game by tapping on the load icon on the menu screen.</p>
108
- <h3>Collect dragon balls and summon Shenron for wishes</h3>
109
- <p>As mentioned earlier, you can collect dragon balls in the game and use them to summon Shenron, the eternal dragon. Shenron can grant you any wish that you desire, such as increasing your stats, unlocking new skills and transformations, getting rare items and equipment, and more. However, you can only use Shenron once per day, so choose your wish wisely.</p>
110
- <h3>Use items and equipment to boost your stats and abilities</h3>
111
- <p>You can find various items and equipment in the game that can help you in your adventure. Items are consumable items that you can use to restore your health, energy, or status effects. Equipment are wearable items that you can equip to increase your stats and abilities. You can find items and equipment by completing quests, defeating enemies, opening chests, or buying them from shops.</p>
112
- <p>You can access your inventory by tapping on the bag icon on the menu screen. You can use items by tapping on them and selecting the use option. You can equip equipment by tapping on them and selecting the equip option. You can also sell or discard items and equipment that you don't need by tapping on them and selecting the sell or discard option.</p>
113
- <h3>Join online multiplayer mode to play with other players</h3>
114
- <p>The game also has an online multiplayer mode that lets you play with other players around the world. You can join online multiplayer mode by tapping on the multiplayer icon on the menu screen. You will need an internet connection to play online multiplayer mode.</p>
115
- <p>In online multiplayer mode, you can choose between cooperative mode or competitive mode. In cooperative mode, you can team up with other players to complete missions, fight enemies, or challenge bosses. In competitive mode, you can fight against other players in PvP battles.</p>
116
- <p>You can also chat with other players by tapping on the chat icon on the menu screen. You can send text messages or voice messages to other players. You can also trade items and equipment with other players by tapping on the trade icon on the menu screen.</p>
117
- <h2>Conclusion</h2>
118
- <p>DBZ RPG APK is a fan-made game that lets you play as any Dragon Ball Z character in an open-world RPG. The game is not available on the Google Play Store, so you have to download it from a third-party source as an APK file. The game features many characters from the Dragon Ball Z series, a large open world that recreates the locations from the anime, a combat system that lets you use various attacks and techniques from the anime, a customization system that lets you change your appearance, Continuing the article: skills, and transformations, and an online multiplayer mode that lets you play with other players. If you are a fan of Dragon Ball Z, you should definitely try DBZ RPG APK. It is a game that will make you feel like you are part of the Dragon Ball Z universe. You can download it from [DBZ RPG APK Download] and follow the steps in this article to install and play it. Have fun and enjoy playing DBZ RPG APK! <h2>FAQs</h2>
119
- <p>Here are some frequently asked questions about DBZ RPG APK:</p>
120
- <h3>Q: Is DBZ RPG APK safe to download and install?</h3>
121
- <p>A: Yes, DBZ RPG APK is safe to download and install as long as you get it from a reliable source, such as [DBZ RPG APK Download]. However, you should always be careful when downloading and installing apps from unknown sources, as they might contain viruses or malware. You should also scan your device with an antivirus app before and after installing DBZ RPG APK.</p>
122
- <h3>Q: Is DBZ RPG APK legal to play?</h3>
123
- <p>A: DBZ RPG APK is an unofficial fan-made game that is not affiliated with or endorsed by the official Dragon Ball Z franchise or its creators. Therefore, it might violate some intellectual property rights or terms of service of the original owners. However, as long as you play it for personal and non-commercial use, you should not face any legal issues. However, we are not responsible for any consequences that might arise from playing DBZ RPG APK.</p>
124
- <h3>Q: How can I update DBZ RPG APK to the latest version?</h3>
125
- <p>A: To update DBZ RPG APK to the latest version, you will need to download and install the new APK file from the same source where you got the previous one. You can check for updates by visiting [DBZ RPG APK Download] or by following their social media accounts. You can also enable notifications on your device to get notified when a new update is available.</p>
126
- <h3>Q: How can I contact the developers of DBZ RPG APK?</h3>
127
- <p>A: You can contact the developers of DBZ RPG APK by visiting their website or by sending them an email at [[email protected]]. You can also follow them on their social media accounts, such as Facebook, Twitter, Instagram, and YouTube. You can give them feedback, suggestions, bug reports, or any other inquiries that you might have.</p>
128
- <h3>Q: How can I support the developers of DBZ RPG APK?</h3>
129
- <p>A: You can support the developers of DBZ RPG APK by donating to them via PayPal or Patreon. You can also support them by sharing their game with your friends and family, by rating and reviewing their game on various platforms, and by following and engaging with them on their social media accounts.</p> 197e85843d<br />
130
- <br />
131
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1phancelerku/anime-remove-background/Download My Eternal Season 5 Episode 1 - The Best Filipino Drama Ever.md DELETED
@@ -1,120 +0,0 @@
1
-
2
- <h1>My Eternal Season 5 Episode 1 Download: How to Watch the Latest Episode of the Hit Philippine Drama</h1>
3
- <p>If you are a fan of Philippine dramas, you have probably heard of <strong>My Eternal</strong>, one of the most successful and acclaimed series in the country. My Eternal is a romantic drama that follows the star-crossed love story of Daniel and Katerina, who are separated by fate, family, and revenge. The series has been airing since 2012 and has won numerous awards and accolades, both locally and internationally. It has also gained a loyal fan base that eagerly awaits every new episode.</p>
4
- <h2>my eternal season 5 episode 1 download</h2><br /><p><b><b>Download Zip</b> &gt; <a href="https://jinyurl.com/2uNUDy">https://jinyurl.com/2uNUDy</a></b></p><br /><br />
5
- <p>But how can you watch <strong>My Eternal season 5 episode 1</strong>, which premiered on June 19, 2023? And what can you expect from this latest installment of the saga? In this article, we will tell you everything you need to know about <strong>My Eternal season 5 episode 1 download</strong>, including how to do it legally and safely, what to expect from the plot, and where to find more information about the show. Read on to find out more!</p>
6
- <h2>What is My Eternal and why is it popular?</h2>
7
- <p>My Eternal is a Philippine drama series produced by ABS-CBN, the country's largest media network. It is based on the classic novel <em>Wuthering Heights</em> by Emily Brontë, but with a modern twist. The series revolves around Daniel (Coco Martin) and Katerina (Julia Montes), who are childhood friends turned lovers. However, their relationship is complicated by their families' feud, their social status, and their personal vendettas. Daniel is the illegitimate son of Marco (Richard Gomez), a wealthy landowner who abandoned his true love Emily (Dawn Zulueta) for another woman. Katerina is the daughter of Tomas (Joel Torre), a poor worker who hates Marco for his betrayal. Emily returns to seek revenge on Marco and his family, while Daniel becomes her pawn in her scheme. Katerina marries Nathan (Paulo Avelino), Marco's legitimate son, out of obligation, but still loves Daniel. The series follows their struggles, sacrifices, and tragedies as they try to overcome their obstacles and find their eternal happiness.</p>
8
- <p>My Eternal is popular because it has a captivating story, a talented cast, a beautiful cinematography, and a memorable soundtrack. The series has been praised for its realistic portrayal of Filipino culture, values, and history, as well as its exploration of themes such as love, family, loyalty, betrayal, forgiveness, and redemption. The series has also been recognized for its high ratings and awards, both in the Philippines and abroad. It has won several trophies at the PMPC Star Awards for TV, the Golden Screen TV Awards, the Gawad Tanglaw Awards, the Anak TV Seal Awards, and the <h2>How to download My Eternal season 5 episode 1 legally and safely?</h2>
9
- <p>If you want to watch <strong>My Eternal season 5 episode 1</strong>, you might be tempted to look for illegal or pirated copies online. However, this is not a good idea, as you might end up with low-quality videos, malware, viruses, or scams that could harm your device or compromise your personal information. Moreover, downloading or streaming My Eternal from unauthorized sources is a violation of intellectual property rights and could get you in trouble with the law.</p>
10
- <p>Fortunately, there are legal and safe ways to download <strong>My Eternal season 5 episode 1</strong> and enjoy it at your own convenience. Here are some of the official platforms and websites that offer My Eternal season 5 episode 1 for download:</p>
11
- <ul>
12
- <li><strong>Youku</strong>: Youku is a Chinese video streaming service that has the exclusive rights to air My Eternal in China. You can download My Eternal season 5 episode 1 from Youku for free, but you will need to create an account and use a VPN to access the website from outside China. You can also watch My Eternal with Chinese subtitles on Youku.</li>
13
- <li><strong>iQiyi</strong>: iQiyi is another Chinese video streaming service that has the rights to air My Eternal in some Asian countries, such as Singapore, Malaysia, Indonesia, Thailand, and Vietnam. You can download My Eternal season 5 episode 1 from iQiyi for free, but you will need to create an account and use a VPN to access the website from other regions. You can also watch My Eternal with English or local subtitles on iQiyi.</li>
14
- <li><strong>ABS-CBN International Sales</strong>: ABS-CBN International Sales is the official distributor of My Eternal and other ABS-CBN shows worldwide. You can inquire about how to download My Eternal season 5 episode 1 from ABS-CBN International Sales by visiting their website and filling out a form. You can also watch My Eternal with English subtitles on ABS-CBN International Sales.</li>
15
- </ul>
16
- <p>These are some of the advantages and disadvantages of downloading <strong>My Eternal season 5 episode 1</strong> from different sources:</p>
17
- <table>
18
- <tr>
19
- <th>Source</th>
20
- <th>Advantages</th>
21
- <th>Disadvantages</th>
22
- </tr>
23
- <tr>
24
- <td>Youku</td>
25
- <td>- Free<br>- High-quality video<br>- Chinese subtitles</td>
26
- <td>- Requires account and VPN<br>- Geoblocked outside China<br>- No English subtitles</td>
27
- </tr>
28
- <tr>
29
- <td>iQiyi</td>
30
- <td>- Free<br>- High-quality video<br>- English or local subtitles</td>
31
- <td>- Requires account and VPN<br>- Geoblocked outside some Asian countries<br>- Limited availability</td>
32
- </tr>
33
- <tr>
34
- <td>ABS-CBN International Sales</td>
35
- <td>- Official distributor<br>- High-quality video<br>- English subtitles</td>
36
- <td>- Requires inquiry and payment<br>- Not available in some regions<br>- No local subtitles</td>
37
- </tr>
38
- </table>
39
- <p>When downloading <strong>My Eternal season 5 episode 1</strong>, you should also follow these tips and precautions to avoid malware, viruses, and scams:</p>
40
- <p>My Eternal End Episode English YouTube<br />
41
- My Eternal ABS-CBN International Sales<br />
42
- My Eternal Season 5 Episode 1 FzMovies<br />
43
- My Eternal Star-Crossed Lovers Drama<br />
44
- My Eternal Walang Hanggan Full Episodes<br />
45
- My Eternal Coco Martin and Julia Montes<br />
46
- My Eternal Synopsis and Cast Guide<br />
47
- My Eternal Revenge and Betrayal Plot<br />
48
- My Eternal Montenegro Winery Setting<br />
49
- My Eternal Daniel and Katerina Love Story<br />
50
- My Eternal Emily's Return for Vengeance<br />
51
- My Eternal Marco's Secret Son Twist<br />
52
- My Eternal Margaret's Evil Schemes<br />
53
- My Eternal Nathan and Katerina Marriage<br />
54
- My Eternal Daniel's Rise to Power<br />
55
- My Eternal ABS-CBN Entertainment Channel<br />
56
- My Eternal Official Website and Facebook Page<br />
57
- My Eternal Twitter and Instagram Updates<br />
58
- My Eternal Comments and Reviews Online<br />
59
- My Eternal Trailer and Teaser Videos<br />
60
- My Eternal Theme Song and Soundtrack<br />
61
- My Eternal Awards and Nominations<br />
62
- My Eternal Ratings and Viewership<br />
63
- My Eternal Behind the Scenes and Bloopers<br />
64
- My Eternal Cast Interviews and Photoshoots<br />
65
- My Eternal Fan Art and Merchandise<br />
66
- My Eternal Netflix and iWant Streaming<br />
67
- My Eternal DVD and Blu-ray Release<br />
68
- My Eternal Torrent and Magnet Link Download<br />
69
- My Eternal Subtitles and Dubbing Options<br />
70
- My Eternal Season 5 Episode 1 Recap and Analysis<br />
71
- My Eternal Season 5 Episode 1 Spoilers and Predictions<br />
72
- My Eternal Season 5 Episode 1 Watch Online Free<br />
73
- My Eternal Season 5 Episode 1 HD Quality Download<br />
74
- My Eternal Season 5 Episode 1 MP4 and MP3 Format Download<br />
75
- My Eternal Season 5 Episode 1 3GP and AVI Format Download<br />
76
- My Eternal Season 5 Episode 1 720p and 480p Resolution Download<br />
77
- My Eternal Season 5 Episode 1 300MB and 500MB Size Download<br />
78
- My Eternal Season 5 Episode 1 Tamilrockers and Movierulz Download<br />
79
- My Eternal Season 5 Episode 1 Worldfree4u and Filmywap Download</p>
80
- <ul>
81
- <li><strong>Use a reliable antivirus software and VPN service.</strong> These will help you protect your device and data from malicious attacks and unwanted tracking.</li>
82
- <li><strong>Check the source and reputation of the website.</strong> Do not download or stream My Eternal from unknown or suspicious websites that might contain harmful content or phishing links.</li>
83
- <li><strong>Read the reviews and ratings of the website.</strong> See what other users have to say about the quality and safety of the website before downloading or streaming My Eternal from it.</li>
84
- <li><strong>Avoid clicking on pop-ups or ads.</strong> These might redirect you to unwanted or harmful websites that might infect your device or steal your information.</li>
85
- <li><strong>Report any illegal or pirated copies of My Eternal.</strong> If you encounter any unauthorized or infringing copies of My Eternal online, you should report them to the appropriate authorities or platforms to help stop piracy and protect intellectual property rights.</li>
86
- </ul>
87
- <h2>What to expect from My Eternal season 5 episode 1?</h2>
88
- <p>If you are wondering what will happen in <strong>My Eternal season 5 episode 1</strong>, here is a spoiler-free overview of the events and twists in the latest installment of the drama:</p>
89
- <ul>
90
- <li><strong>The aftermath of Daniel's death.</strong> The shocking finale of season 4 left fans in tears as Daniel (Coco Martin) sacrificed himself to save Katerina (Julia Montes) from a bomb planted by Nathan (Paulo Avelino), who had gone insane with jealousy and hatred. Katerina was devastated by Daniel's death and blamed herself for his fate. She also had to deal with Nathan's harassment and Marco's (Richard Gomez) wrath, who blamed Daniel for Emily's (Dawn Zulueta) death.</li>
91
- <li><strong>The return of Daniel.</strong> However, Daniel was not really dead, but was saved by a mysterious woman named Lorraine (Maja Salvador), who nursed him back to health and fell in love with him. Daniel lost his memory and did not remember anything about his past or Katerina. He assumed a new identity as Franco, a wealthy businessman who was Lorraine's fiancé. He also became friends with Johanna (Melissa Ricks), Marco's daughter, who had a crush on him.</li>
92
- <li><strong>The reunion of Daniel and Katerina.</strong> Fate brought Daniel and Katerina together again when they met at a charity event organized by Franco. Katerina recognized Daniel immediately, but he did not remember her. She tried to jog his memory and win him back, but faced resistance from Lorraine, who was obsessed with Franco and willing to do anything to keep him. She also had to deal with Nathan, who escaped from the mental hospital and vowed to kill Daniel and Katerina.</li>
93
- </ul>
94
- <p>These are some of the reactions and reviews of <strong>My Eternal season 5 episode 1</strong> from critics and fans:</p>
95
- <blockquote>
96
- <p>"My Eternal season 5 episode 1 was a roller coaster of emotions. I cried, I laughed, I screamed, I swooned. The acting, the writing, the directing, the music, everything was superb. Coco Martin and Julia Montes have such amazing chemistry and they make me feel their love and pain. Maja Salvador is also a great addition to the cast and she plays the villain role very well. I can't wait to see what will happen next in this epic drama." - Maria, a fan from Manila</p>
97
- </blockquote>
98
- <blockquote>
99
- <p>"My Eternal season 5 episode 1 delivered on its promise of being the most explosive and exciting season premiere yet. The show continues to impress with its gripping story, stellar performances, stunning visuals, and captivating soundtrack. My Eternal is not just a drama, it's a phenomenon that transcends borders and cultures. It is one of the best Philippine dramas ever made and deserves all the praise and recognition it gets." - John, a critic from Singapore</p>
100
- </blockquote>
101
- <p>If you want to see what will happen next in My Eternal, you can watch the teasers and trailers of <strong>My Eternal season 5 episode 2</strong> on the official YouTube channel of ABS-CBN Entertainment. You can also follow the official social media accounts of My Eternal on Facebook, Twitter, and Instagram for more updates, behind-the-scenes, and exclusive content.</p>
102
- <h3>Conclusion</h3>
103
- <p>In conclusion, <strong>My Eternal season 5 episode 1</strong> is a must-watch for fans of Philippine dramas and lovers of romance. It is the latest episode of the hit series My Eternal, which tells the story of Daniel and Katerina, two star-crossed lovers who face many challenges and obstacles in their quest for eternal happiness. You can download My Eternal season 5 episode 1 legally and safely from various platforms and websites, such as Youku, iQiyi, or ABS-CBN International Sales. You can also expect a lot of drama, suspense, action, and romance from My Eternal season 5 episode 1, as well as from the upcoming episodes of the series.</p>
104
- <p>If you enjoyed this article, please share it with your friends and family who are also fans of My Eternal. You can also leave your comments and feedback below. We would love to hear from you!</p>
105
- <h4>FAQs</h4>
106
- <p>Here are some frequently asked questions and answers about <strong>My Eternal season 5 episode 1</strong>:</p>
107
- <ol>
108
- <li><strong>When will My Eternal season 5 episode 1 be available for download?</strong><br>
109
- My Eternal season 5 episode 1 premiered on June 19, 2023 on ABS-CBN in the Philippines. It will be available for download on different platforms and websites within a few days or weeks after its broadcast date.</li>
110
- <li><strong>How much does it cost to download My Eternal season 5 episode 1?</strong><br>
111
- The cost of downloading My Eternal season 5 episode 1 depends on the source and the quality of the video. Some sources offer My Eternal season 5 episode 1 for free, while others require payment or subscription fees. You should compare the prices and the features of each source before downloading My Eternal season 5 episode 1.</li>
112
- <li><strong>Is it legal to download My Eternal season 5 episode 1?</strong><br>
113
- It is legal to download My Eternal season 5 episode 1 from the official platforms and websites that have the rights and licenses to distribute the show. However, it is illegal to download or stream My Eternal from unauthorized or pirated sources that infringe on the intellectual property rights of the creators and producers of the show.</li>
114
- <li><strong>Is it safe to download My Eternal season 5 episode 1?</strong><br>
115
- It is safe to download My Eternal season 5 episode 1 from the official platforms and websites that have the security and quality standards to protect your device and data. However, it is unsafe to download or stream My Eternal from unknown or suspicious sources that might contain malware, viruses, or scams that could harm your device or compromise your personal information.</li>
116
- <li><strong>Where can I find more information about My Eternal?</strong><br>
117
- You can find more information about My Eternal on the official website of ABS-CBN Entertainment, where you can also watch the episodes online. You can also follow the official social media accounts of My Eternal on Facebook, Twitter, and Instagram for more updates, behind-the-scenes, and exclusive content. You can also join the online communities and forums of My Eternal fans, where you can discuss and share your opinions and insights about the show.</li>
118
- </ol></p> 197e85843d<br />
119
- <br />
120
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/4Taps/SadTalker/src/utils/face_enhancer.py DELETED
@@ -1,60 +0,0 @@
1
- import os
2
- from basicsr.utils import imwrite
3
-
4
- from gfpgan import GFPGANer
5
-
6
- from tqdm import tqdm
7
-
8
- def enhancer(images, method='gfpgan'):
9
-
10
- # ------------------------ set up GFPGAN restorer ------------------------
11
- if method == 'gfpgan':
12
- arch = 'clean'
13
- channel_multiplier = 2
14
- model_name = 'GFPGANv1.4'
15
- url = 'https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.4.pth'
16
- elif method == 'RestoreFormer':
17
- arch = 'RestoreFormer'
18
- channel_multiplier = 2
19
- model_name = 'RestoreFormer'
20
- url = 'https://github.com/TencentARC/GFPGAN/releases/download/v1.3.4/RestoreFormer.pth'
21
- elif method == 'codeformer':
22
- arch = 'CodeFormer'
23
- channel_multiplier = 2
24
- model_name = 'CodeFormer'
25
- url = 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/codeformer.pth'
26
- else:
27
- raise ValueError(f'Wrong model version {method}.')
28
-
29
- # determine model paths
30
- model_path = os.path.join('experiments/pretrained_models', model_name + '.pth')
31
-
32
- if not os.path.isfile(model_path):
33
- model_path = os.path.join('checkpoints', model_name + '.pth')
34
-
35
- if not os.path.isfile(model_path):
36
- # download pre-trained models from url
37
- model_path = url
38
-
39
- restorer = GFPGANer(
40
- model_path=model_path,
41
- upscale=2,
42
- arch=arch,
43
- channel_multiplier=channel_multiplier,
44
- bg_upsampler=None)
45
-
46
- # ------------------------ restore ------------------------
47
- restored_img = []
48
- for idx in tqdm(range(len(images)), 'Face Enhancer:'):
49
-
50
- # restore faces and background if necessary
51
- cropped_faces, restored_faces, _ = restorer.enhance(
52
- images[idx],
53
- has_aligned=True,
54
- only_center_face=False,
55
- paste_back=True,
56
- weight=0.5)
57
-
58
- restored_img += restored_faces
59
-
60
- return restored_img
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/801artistry/RVC801/infer/lib/infer_pack/modules.py DELETED
@@ -1,521 +0,0 @@
1
- import copy
2
- import math
3
-
4
- import numpy as np
5
- import scipy
6
- import torch
7
- from torch import nn
8
- from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d
9
- from torch.nn import functional as F
10
- from torch.nn.utils import remove_weight_norm, weight_norm
11
-
12
- from infer.lib.infer_pack import commons
13
- from infer.lib.infer_pack.commons import get_padding, init_weights
14
- from infer.lib.infer_pack.transforms import piecewise_rational_quadratic_transform
15
-
16
- LRELU_SLOPE = 0.1
17
-
18
-
19
- class LayerNorm(nn.Module):
20
- def __init__(self, channels, eps=1e-5):
21
- super().__init__()
22
- self.channels = channels
23
- self.eps = eps
24
-
25
- self.gamma = nn.Parameter(torch.ones(channels))
26
- self.beta = nn.Parameter(torch.zeros(channels))
27
-
28
- def forward(self, x):
29
- x = x.transpose(1, -1)
30
- x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
31
- return x.transpose(1, -1)
32
-
33
-
34
- class ConvReluNorm(nn.Module):
35
- def __init__(
36
- self,
37
- in_channels,
38
- hidden_channels,
39
- out_channels,
40
- kernel_size,
41
- n_layers,
42
- p_dropout,
43
- ):
44
- super().__init__()
45
- self.in_channels = in_channels
46
- self.hidden_channels = hidden_channels
47
- self.out_channels = out_channels
48
- self.kernel_size = kernel_size
49
- self.n_layers = n_layers
50
- self.p_dropout = p_dropout
51
- assert n_layers > 1, "Number of layers should be larger than 0."
52
-
53
- self.conv_layers = nn.ModuleList()
54
- self.norm_layers = nn.ModuleList()
55
- self.conv_layers.append(
56
- nn.Conv1d(
57
- in_channels, hidden_channels, kernel_size, padding=kernel_size // 2
58
- )
59
- )
60
- self.norm_layers.append(LayerNorm(hidden_channels))
61
- self.relu_drop = nn.Sequential(nn.ReLU(), nn.Dropout(p_dropout))
62
- for _ in range(n_layers - 1):
63
- self.conv_layers.append(
64
- nn.Conv1d(
65
- hidden_channels,
66
- hidden_channels,
67
- kernel_size,
68
- padding=kernel_size // 2,
69
- )
70
- )
71
- self.norm_layers.append(LayerNorm(hidden_channels))
72
- self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
73
- self.proj.weight.data.zero_()
74
- self.proj.bias.data.zero_()
75
-
76
- def forward(self, x, x_mask):
77
- x_org = x
78
- for i in range(self.n_layers):
79
- x = self.conv_layers[i](x * x_mask)
80
- x = self.norm_layers[i](x)
81
- x = self.relu_drop(x)
82
- x = x_org + self.proj(x)
83
- return x * x_mask
84
-
85
-
86
- class DDSConv(nn.Module):
87
- """
88
- Dialted and Depth-Separable Convolution
89
- """
90
-
91
- def __init__(self, channels, kernel_size, n_layers, p_dropout=0.0):
92
- super().__init__()
93
- self.channels = channels
94
- self.kernel_size = kernel_size
95
- self.n_layers = n_layers
96
- self.p_dropout = p_dropout
97
-
98
- self.drop = nn.Dropout(p_dropout)
99
- self.convs_sep = nn.ModuleList()
100
- self.convs_1x1 = nn.ModuleList()
101
- self.norms_1 = nn.ModuleList()
102
- self.norms_2 = nn.ModuleList()
103
- for i in range(n_layers):
104
- dilation = kernel_size**i
105
- padding = (kernel_size * dilation - dilation) // 2
106
- self.convs_sep.append(
107
- nn.Conv1d(
108
- channels,
109
- channels,
110
- kernel_size,
111
- groups=channels,
112
- dilation=dilation,
113
- padding=padding,
114
- )
115
- )
116
- self.convs_1x1.append(nn.Conv1d(channels, channels, 1))
117
- self.norms_1.append(LayerNorm(channels))
118
- self.norms_2.append(LayerNorm(channels))
119
-
120
- def forward(self, x, x_mask, g=None):
121
- if g is not None:
122
- x = x + g
123
- for i in range(self.n_layers):
124
- y = self.convs_sep[i](x * x_mask)
125
- y = self.norms_1[i](y)
126
- y = F.gelu(y)
127
- y = self.convs_1x1[i](y)
128
- y = self.norms_2[i](y)
129
- y = F.gelu(y)
130
- y = self.drop(y)
131
- x = x + y
132
- return x * x_mask
133
-
134
-
135
- class WN(torch.nn.Module):
136
- def __init__(
137
- self,
138
- hidden_channels,
139
- kernel_size,
140
- dilation_rate,
141
- n_layers,
142
- gin_channels=0,
143
- p_dropout=0,
144
- ):
145
- super(WN, self).__init__()
146
- assert kernel_size % 2 == 1
147
- self.hidden_channels = hidden_channels
148
- self.kernel_size = (kernel_size,)
149
- self.dilation_rate = dilation_rate
150
- self.n_layers = n_layers
151
- self.gin_channels = gin_channels
152
- self.p_dropout = p_dropout
153
-
154
- self.in_layers = torch.nn.ModuleList()
155
- self.res_skip_layers = torch.nn.ModuleList()
156
- self.drop = nn.Dropout(p_dropout)
157
-
158
- if gin_channels != 0:
159
- cond_layer = torch.nn.Conv1d(
160
- gin_channels, 2 * hidden_channels * n_layers, 1
161
- )
162
- self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name="weight")
163
-
164
- for i in range(n_layers):
165
- dilation = dilation_rate**i
166
- padding = int((kernel_size * dilation - dilation) / 2)
167
- in_layer = torch.nn.Conv1d(
168
- hidden_channels,
169
- 2 * hidden_channels,
170
- kernel_size,
171
- dilation=dilation,
172
- padding=padding,
173
- )
174
- in_layer = torch.nn.utils.weight_norm(in_layer, name="weight")
175
- self.in_layers.append(in_layer)
176
-
177
- # last one is not necessary
178
- if i < n_layers - 1:
179
- res_skip_channels = 2 * hidden_channels
180
- else:
181
- res_skip_channels = hidden_channels
182
-
183
- res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1)
184
- res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name="weight")
185
- self.res_skip_layers.append(res_skip_layer)
186
-
187
- def forward(self, x, x_mask, g=None, **kwargs):
188
- output = torch.zeros_like(x)
189
- n_channels_tensor = torch.IntTensor([self.hidden_channels])
190
-
191
- if g is not None:
192
- g = self.cond_layer(g)
193
-
194
- for i in range(self.n_layers):
195
- x_in = self.in_layers[i](x)
196
- if g is not None:
197
- cond_offset = i * 2 * self.hidden_channels
198
- g_l = g[:, cond_offset : cond_offset + 2 * self.hidden_channels, :]
199
- else:
200
- g_l = torch.zeros_like(x_in)
201
-
202
- acts = commons.fused_add_tanh_sigmoid_multiply(x_in, g_l, n_channels_tensor)
203
- acts = self.drop(acts)
204
-
205
- res_skip_acts = self.res_skip_layers[i](acts)
206
- if i < self.n_layers - 1:
207
- res_acts = res_skip_acts[:, : self.hidden_channels, :]
208
- x = (x + res_acts) * x_mask
209
- output = output + res_skip_acts[:, self.hidden_channels :, :]
210
- else:
211
- output = output + res_skip_acts
212
- return output * x_mask
213
-
214
- def remove_weight_norm(self):
215
- if self.gin_channels != 0:
216
- torch.nn.utils.remove_weight_norm(self.cond_layer)
217
- for l in self.in_layers:
218
- torch.nn.utils.remove_weight_norm(l)
219
- for l in self.res_skip_layers:
220
- torch.nn.utils.remove_weight_norm(l)
221
-
222
-
223
- class ResBlock1(torch.nn.Module):
224
- def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
225
- super(ResBlock1, self).__init__()
226
- self.convs1 = nn.ModuleList(
227
- [
228
- weight_norm(
229
- Conv1d(
230
- channels,
231
- channels,
232
- kernel_size,
233
- 1,
234
- dilation=dilation[0],
235
- padding=get_padding(kernel_size, dilation[0]),
236
- )
237
- ),
238
- weight_norm(
239
- Conv1d(
240
- channels,
241
- channels,
242
- kernel_size,
243
- 1,
244
- dilation=dilation[1],
245
- padding=get_padding(kernel_size, dilation[1]),
246
- )
247
- ),
248
- weight_norm(
249
- Conv1d(
250
- channels,
251
- channels,
252
- kernel_size,
253
- 1,
254
- dilation=dilation[2],
255
- padding=get_padding(kernel_size, dilation[2]),
256
- )
257
- ),
258
- ]
259
- )
260
- self.convs1.apply(init_weights)
261
-
262
- self.convs2 = nn.ModuleList(
263
- [
264
- weight_norm(
265
- Conv1d(
266
- channels,
267
- channels,
268
- kernel_size,
269
- 1,
270
- dilation=1,
271
- padding=get_padding(kernel_size, 1),
272
- )
273
- ),
274
- weight_norm(
275
- Conv1d(
276
- channels,
277
- channels,
278
- kernel_size,
279
- 1,
280
- dilation=1,
281
- padding=get_padding(kernel_size, 1),
282
- )
283
- ),
284
- weight_norm(
285
- Conv1d(
286
- channels,
287
- channels,
288
- kernel_size,
289
- 1,
290
- dilation=1,
291
- padding=get_padding(kernel_size, 1),
292
- )
293
- ),
294
- ]
295
- )
296
- self.convs2.apply(init_weights)
297
-
298
- def forward(self, x, x_mask=None):
299
- for c1, c2 in zip(self.convs1, self.convs2):
300
- xt = F.leaky_relu(x, LRELU_SLOPE)
301
- if x_mask is not None:
302
- xt = xt * x_mask
303
- xt = c1(xt)
304
- xt = F.leaky_relu(xt, LRELU_SLOPE)
305
- if x_mask is not None:
306
- xt = xt * x_mask
307
- xt = c2(xt)
308
- x = xt + x
309
- if x_mask is not None:
310
- x = x * x_mask
311
- return x
312
-
313
- def remove_weight_norm(self):
314
- for l in self.convs1:
315
- remove_weight_norm(l)
316
- for l in self.convs2:
317
- remove_weight_norm(l)
318
-
319
-
320
- class ResBlock2(torch.nn.Module):
321
- def __init__(self, channels, kernel_size=3, dilation=(1, 3)):
322
- super(ResBlock2, self).__init__()
323
- self.convs = nn.ModuleList(
324
- [
325
- weight_norm(
326
- Conv1d(
327
- channels,
328
- channels,
329
- kernel_size,
330
- 1,
331
- dilation=dilation[0],
332
- padding=get_padding(kernel_size, dilation[0]),
333
- )
334
- ),
335
- weight_norm(
336
- Conv1d(
337
- channels,
338
- channels,
339
- kernel_size,
340
- 1,
341
- dilation=dilation[1],
342
- padding=get_padding(kernel_size, dilation[1]),
343
- )
344
- ),
345
- ]
346
- )
347
- self.convs.apply(init_weights)
348
-
349
- def forward(self, x, x_mask=None):
350
- for c in self.convs:
351
- xt = F.leaky_relu(x, LRELU_SLOPE)
352
- if x_mask is not None:
353
- xt = xt * x_mask
354
- xt = c(xt)
355
- x = xt + x
356
- if x_mask is not None:
357
- x = x * x_mask
358
- return x
359
-
360
- def remove_weight_norm(self):
361
- for l in self.convs:
362
- remove_weight_norm(l)
363
-
364
-
365
- class Log(nn.Module):
366
- def forward(self, x, x_mask, reverse=False, **kwargs):
367
- if not reverse:
368
- y = torch.log(torch.clamp_min(x, 1e-5)) * x_mask
369
- logdet = torch.sum(-y, [1, 2])
370
- return y, logdet
371
- else:
372
- x = torch.exp(x) * x_mask
373
- return x
374
-
375
-
376
- class Flip(nn.Module):
377
- def forward(self, x, *args, reverse=False, **kwargs):
378
- x = torch.flip(x, [1])
379
- if not reverse:
380
- logdet = torch.zeros(x.size(0)).to(dtype=x.dtype, device=x.device)
381
- return x, logdet
382
- else:
383
- return x
384
-
385
-
386
- class ElementwiseAffine(nn.Module):
387
- def __init__(self, channels):
388
- super().__init__()
389
- self.channels = channels
390
- self.m = nn.Parameter(torch.zeros(channels, 1))
391
- self.logs = nn.Parameter(torch.zeros(channels, 1))
392
-
393
- def forward(self, x, x_mask, reverse=False, **kwargs):
394
- if not reverse:
395
- y = self.m + torch.exp(self.logs) * x
396
- y = y * x_mask
397
- logdet = torch.sum(self.logs * x_mask, [1, 2])
398
- return y, logdet
399
- else:
400
- x = (x - self.m) * torch.exp(-self.logs) * x_mask
401
- return x
402
-
403
-
404
- class ResidualCouplingLayer(nn.Module):
405
- def __init__(
406
- self,
407
- channels,
408
- hidden_channels,
409
- kernel_size,
410
- dilation_rate,
411
- n_layers,
412
- p_dropout=0,
413
- gin_channels=0,
414
- mean_only=False,
415
- ):
416
- assert channels % 2 == 0, "channels should be divisible by 2"
417
- super().__init__()
418
- self.channels = channels
419
- self.hidden_channels = hidden_channels
420
- self.kernel_size = kernel_size
421
- self.dilation_rate = dilation_rate
422
- self.n_layers = n_layers
423
- self.half_channels = channels // 2
424
- self.mean_only = mean_only
425
-
426
- self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
427
- self.enc = WN(
428
- hidden_channels,
429
- kernel_size,
430
- dilation_rate,
431
- n_layers,
432
- p_dropout=p_dropout,
433
- gin_channels=gin_channels,
434
- )
435
- self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
436
- self.post.weight.data.zero_()
437
- self.post.bias.data.zero_()
438
-
439
- def forward(self, x, x_mask, g=None, reverse=False):
440
- x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
441
- h = self.pre(x0) * x_mask
442
- h = self.enc(h, x_mask, g=g)
443
- stats = self.post(h) * x_mask
444
- if not self.mean_only:
445
- m, logs = torch.split(stats, [self.half_channels] * 2, 1)
446
- else:
447
- m = stats
448
- logs = torch.zeros_like(m)
449
-
450
- if not reverse:
451
- x1 = m + x1 * torch.exp(logs) * x_mask
452
- x = torch.cat([x0, x1], 1)
453
- logdet = torch.sum(logs, [1, 2])
454
- return x, logdet
455
- else:
456
- x1 = (x1 - m) * torch.exp(-logs) * x_mask
457
- x = torch.cat([x0, x1], 1)
458
- return x
459
-
460
- def remove_weight_norm(self):
461
- self.enc.remove_weight_norm()
462
-
463
-
464
- class ConvFlow(nn.Module):
465
- def __init__(
466
- self,
467
- in_channels,
468
- filter_channels,
469
- kernel_size,
470
- n_layers,
471
- num_bins=10,
472
- tail_bound=5.0,
473
- ):
474
- super().__init__()
475
- self.in_channels = in_channels
476
- self.filter_channels = filter_channels
477
- self.kernel_size = kernel_size
478
- self.n_layers = n_layers
479
- self.num_bins = num_bins
480
- self.tail_bound = tail_bound
481
- self.half_channels = in_channels // 2
482
-
483
- self.pre = nn.Conv1d(self.half_channels, filter_channels, 1)
484
- self.convs = DDSConv(filter_channels, kernel_size, n_layers, p_dropout=0.0)
485
- self.proj = nn.Conv1d(
486
- filter_channels, self.half_channels * (num_bins * 3 - 1), 1
487
- )
488
- self.proj.weight.data.zero_()
489
- self.proj.bias.data.zero_()
490
-
491
- def forward(self, x, x_mask, g=None, reverse=False):
492
- x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
493
- h = self.pre(x0)
494
- h = self.convs(h, x_mask, g=g)
495
- h = self.proj(h) * x_mask
496
-
497
- b, c, t = x0.shape
498
- h = h.reshape(b, c, -1, t).permute(0, 1, 3, 2) # [b, cx?, t] -> [b, c, t, ?]
499
-
500
- unnormalized_widths = h[..., : self.num_bins] / math.sqrt(self.filter_channels)
501
- unnormalized_heights = h[..., self.num_bins : 2 * self.num_bins] / math.sqrt(
502
- self.filter_channels
503
- )
504
- unnormalized_derivatives = h[..., 2 * self.num_bins :]
505
-
506
- x1, logabsdet = piecewise_rational_quadratic_transform(
507
- x1,
508
- unnormalized_widths,
509
- unnormalized_heights,
510
- unnormalized_derivatives,
511
- inverse=reverse,
512
- tails="linear",
513
- tail_bound=self.tail_bound,
514
- )
515
-
516
- x = torch.cat([x0, x1], 1) * x_mask
517
- logdet = torch.sum(logabsdet * x_mask, [1, 2])
518
- if not reverse:
519
- return x, logdet
520
- else:
521
- return x
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/801artistry/RVC801/tools/calc_rvc_model_similarity.py DELETED
@@ -1,96 +0,0 @@
1
- # This code references https://huggingface.co/JosephusCheung/ASimilarityCalculatior/blob/main/qwerty.py
2
- # Fill in the path of the model to be queried and the root directory of the reference models, and this script will return the similarity between the model to be queried and all reference models.
3
- import os
4
- import logging
5
-
6
- logger = logging.getLogger(__name__)
7
-
8
- import torch
9
- import torch.nn as nn
10
- import torch.nn.functional as F
11
-
12
-
13
- def cal_cross_attn(to_q, to_k, to_v, rand_input):
14
- hidden_dim, embed_dim = to_q.shape
15
- attn_to_q = nn.Linear(hidden_dim, embed_dim, bias=False)
16
- attn_to_k = nn.Linear(hidden_dim, embed_dim, bias=False)
17
- attn_to_v = nn.Linear(hidden_dim, embed_dim, bias=False)
18
- attn_to_q.load_state_dict({"weight": to_q})
19
- attn_to_k.load_state_dict({"weight": to_k})
20
- attn_to_v.load_state_dict({"weight": to_v})
21
-
22
- return torch.einsum(
23
- "ik, jk -> ik",
24
- F.softmax(
25
- torch.einsum("ij, kj -> ik", attn_to_q(rand_input), attn_to_k(rand_input)),
26
- dim=-1,
27
- ),
28
- attn_to_v(rand_input),
29
- )
30
-
31
-
32
- def model_hash(filename):
33
- try:
34
- with open(filename, "rb") as file:
35
- import hashlib
36
-
37
- m = hashlib.sha256()
38
-
39
- file.seek(0x100000)
40
- m.update(file.read(0x10000))
41
- return m.hexdigest()[0:8]
42
- except FileNotFoundError:
43
- return "NOFILE"
44
-
45
-
46
- def eval(model, n, input):
47
- qk = f"enc_p.encoder.attn_layers.{n}.conv_q.weight"
48
- uk = f"enc_p.encoder.attn_layers.{n}.conv_k.weight"
49
- vk = f"enc_p.encoder.attn_layers.{n}.conv_v.weight"
50
- atoq, atok, atov = model[qk][:, :, 0], model[uk][:, :, 0], model[vk][:, :, 0]
51
-
52
- attn = cal_cross_attn(atoq, atok, atov, input)
53
- return attn
54
-
55
-
56
- def main(path, root):
57
- torch.manual_seed(114514)
58
- model_a = torch.load(path, map_location="cpu")["weight"]
59
-
60
- logger.info("Query:\t\t%s\t%s" % (path, model_hash(path)))
61
-
62
- map_attn_a = {}
63
- map_rand_input = {}
64
- for n in range(6):
65
- hidden_dim, embed_dim, _ = model_a[
66
- f"enc_p.encoder.attn_layers.{n}.conv_v.weight"
67
- ].shape
68
- rand_input = torch.randn([embed_dim, hidden_dim])
69
-
70
- map_attn_a[n] = eval(model_a, n, rand_input)
71
- map_rand_input[n] = rand_input
72
-
73
- del model_a
74
-
75
- for name in sorted(list(os.listdir(root))):
76
- path = "%s/%s" % (root, name)
77
- model_b = torch.load(path, map_location="cpu")["weight"]
78
-
79
- sims = []
80
- for n in range(6):
81
- attn_a = map_attn_a[n]
82
- attn_b = eval(model_b, n, map_rand_input[n])
83
-
84
- sim = torch.mean(torch.cosine_similarity(attn_a, attn_b))
85
- sims.append(sim)
86
-
87
- logger.info(
88
- "Reference:\t%s\t%s\t%s"
89
- % (path, model_hash(path), f"{torch.mean(torch.stack(sims)) * 1e2:.2f}%")
90
- )
91
-
92
-
93
- if __name__ == "__main__":
94
- query_path = r"assets\weights\mi v3.pth"
95
- reference_root = r"assets\weights"
96
- main(query_path, reference_root)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AIFILMS/generate_human_motion/pyrender/pyrender/trackball.py DELETED
@@ -1,216 +0,0 @@
1
- """Trackball class for 3D manipulation of viewpoints.
2
- """
3
- import numpy as np
4
-
5
- import trimesh.transformations as transformations
6
-
7
-
8
- class Trackball(object):
9
- """A trackball class for creating camera transforms from mouse movements.
10
- """
11
- STATE_ROTATE = 0
12
- STATE_PAN = 1
13
- STATE_ROLL = 2
14
- STATE_ZOOM = 3
15
-
16
- def __init__(self, pose, size, scale,
17
- target=np.array([0.0, 0.0, 0.0])):
18
- """Initialize a trackball with an initial camera-to-world pose
19
- and the given parameters.
20
-
21
- Parameters
22
- ----------
23
- pose : [4,4]
24
- An initial camera-to-world pose for the trackball.
25
-
26
- size : (float, float)
27
- The width and height of the camera image in pixels.
28
-
29
- scale : float
30
- The diagonal of the scene's bounding box --
31
- used for ensuring translation motions are sufficiently
32
- fast for differently-sized scenes.
33
-
34
- target : (3,) float
35
- The center of the scene in world coordinates.
36
- The trackball will revolve around this point.
37
- """
38
- self._size = np.array(size)
39
- self._scale = float(scale)
40
-
41
- self._pose = pose
42
- self._n_pose = pose
43
-
44
- self._target = target
45
- self._n_target = target
46
-
47
- self._state = Trackball.STATE_ROTATE
48
-
49
- @property
50
- def pose(self):
51
- """autolab_core.RigidTransform : The current camera-to-world pose.
52
- """
53
- return self._n_pose
54
-
55
- def set_state(self, state):
56
- """Set the state of the trackball in order to change the effect of
57
- dragging motions.
58
-
59
- Parameters
60
- ----------
61
- state : int
62
- One of Trackball.STATE_ROTATE, Trackball.STATE_PAN,
63
- Trackball.STATE_ROLL, and Trackball.STATE_ZOOM.
64
- """
65
- self._state = state
66
-
67
- def resize(self, size):
68
- """Resize the window.
69
-
70
- Parameters
71
- ----------
72
- size : (float, float)
73
- The new width and height of the camera image in pixels.
74
- """
75
- self._size = np.array(size)
76
-
77
- def down(self, point):
78
- """Record an initial mouse press at a given point.
79
-
80
- Parameters
81
- ----------
82
- point : (2,) int
83
- The x and y pixel coordinates of the mouse press.
84
- """
85
- self._pdown = np.array(point, dtype=np.float32)
86
- self._pose = self._n_pose
87
- self._target = self._n_target
88
-
89
- def drag(self, point):
90
- """Update the tracball during a drag.
91
-
92
- Parameters
93
- ----------
94
- point : (2,) int
95
- The current x and y pixel coordinates of the mouse during a drag.
96
- This will compute a movement for the trackball with the relative
97
- motion between this point and the one marked by down().
98
- """
99
- point = np.array(point, dtype=np.float32)
100
- dx, dy = point - self._pdown
101
- mindim = 0.3 * np.min(self._size)
102
-
103
- target = self._target
104
- x_axis = self._pose[:3,0].flatten()
105
- y_axis = self._pose[:3,1].flatten()
106
- z_axis = self._pose[:3,2].flatten()
107
- eye = self._pose[:3,3].flatten()
108
-
109
- # Interpret drag as a rotation
110
- if self._state == Trackball.STATE_ROTATE:
111
- x_angle = -dx / mindim
112
- x_rot_mat = transformations.rotation_matrix(
113
- x_angle, y_axis, target
114
- )
115
-
116
- y_angle = dy / mindim
117
- y_rot_mat = transformations.rotation_matrix(
118
- y_angle, x_axis, target
119
- )
120
-
121
- self._n_pose = y_rot_mat.dot(x_rot_mat.dot(self._pose))
122
-
123
- # Interpret drag as a roll about the camera axis
124
- elif self._state == Trackball.STATE_ROLL:
125
- center = self._size / 2.0
126
- v_init = self._pdown - center
127
- v_curr = point - center
128
- v_init = v_init / np.linalg.norm(v_init)
129
- v_curr = v_curr / np.linalg.norm(v_curr)
130
-
131
- theta = (-np.arctan2(v_curr[1], v_curr[0]) +
132
- np.arctan2(v_init[1], v_init[0]))
133
-
134
- rot_mat = transformations.rotation_matrix(theta, z_axis, target)
135
-
136
- self._n_pose = rot_mat.dot(self._pose)
137
-
138
- # Interpret drag as a camera pan in view plane
139
- elif self._state == Trackball.STATE_PAN:
140
- dx = -dx / (5.0 * mindim) * self._scale
141
- dy = -dy / (5.0 * mindim) * self._scale
142
-
143
- translation = dx * x_axis + dy * y_axis
144
- self._n_target = self._target + translation
145
- t_tf = np.eye(4)
146
- t_tf[:3,3] = translation
147
- self._n_pose = t_tf.dot(self._pose)
148
-
149
- # Interpret drag as a zoom motion
150
- elif self._state == Trackball.STATE_ZOOM:
151
- radius = np.linalg.norm(eye - target)
152
- ratio = 0.0
153
- if dy > 0:
154
- ratio = np.exp(abs(dy) / (0.5 * self._size[1])) - 1.0
155
- elif dy < 0:
156
- ratio = 1.0 - np.exp(dy / (0.5 * (self._size[1])))
157
- translation = -np.sign(dy) * ratio * radius * z_axis
158
- t_tf = np.eye(4)
159
- t_tf[:3,3] = translation
160
- self._n_pose = t_tf.dot(self._pose)
161
-
162
- def scroll(self, clicks):
163
- """Zoom using a mouse scroll wheel motion.
164
-
165
- Parameters
166
- ----------
167
- clicks : int
168
- The number of clicks. Positive numbers indicate forward wheel
169
- movement.
170
- """
171
- target = self._target
172
- ratio = 0.90
173
-
174
- mult = 1.0
175
- if clicks > 0:
176
- mult = ratio**clicks
177
- elif clicks < 0:
178
- mult = (1.0 / ratio)**abs(clicks)
179
-
180
- z_axis = self._n_pose[:3,2].flatten()
181
- eye = self._n_pose[:3,3].flatten()
182
- radius = np.linalg.norm(eye - target)
183
- translation = (mult * radius - radius) * z_axis
184
- t_tf = np.eye(4)
185
- t_tf[:3,3] = translation
186
- self._n_pose = t_tf.dot(self._n_pose)
187
-
188
- z_axis = self._pose[:3,2].flatten()
189
- eye = self._pose[:3,3].flatten()
190
- radius = np.linalg.norm(eye - target)
191
- translation = (mult * radius - radius) * z_axis
192
- t_tf = np.eye(4)
193
- t_tf[:3,3] = translation
194
- self._pose = t_tf.dot(self._pose)
195
-
196
- def rotate(self, azimuth, axis=None):
197
- """Rotate the trackball about the "Up" axis by azimuth radians.
198
-
199
- Parameters
200
- ----------
201
- azimuth : float
202
- The number of radians to rotate.
203
- """
204
- target = self._target
205
-
206
- y_axis = self._n_pose[:3,1].flatten()
207
- if axis is not None:
208
- y_axis = axis
209
- x_rot_mat = transformations.rotation_matrix(azimuth, y_axis, target)
210
- self._n_pose = x_rot_mat.dot(self._n_pose)
211
-
212
- y_axis = self._pose[:3,1].flatten()
213
- if axis is not None:
214
- y_axis = axis
215
- x_rot_mat = transformations.rotation_matrix(azimuth, y_axis, target)
216
- self._pose = x_rot_mat.dot(self._pose)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AIGC-Audio/AudioGPT/text_to_speech/modules/tts/syntaspeech/multi_window_disc.py DELETED
@@ -1,136 +0,0 @@
1
- import numpy as np
2
- import torch
3
- import torch.nn as nn
4
-
5
-
6
- class SingleWindowDisc(nn.Module):
7
- def __init__(self, time_length, freq_length=80, kernel=(3, 3), c_in=1, hidden_size=128):
8
- super().__init__()
9
- padding = (kernel[0] // 2, kernel[1] // 2)
10
- self.model = nn.ModuleList([
11
- nn.Sequential(*[
12
- nn.Conv2d(c_in, hidden_size, kernel, (2, 2), padding),
13
- nn.LeakyReLU(0.2, inplace=True),
14
- nn.Dropout2d(0.25),
15
- nn.BatchNorm2d(hidden_size, 0.8)
16
- ]),
17
- nn.Sequential(*[
18
- nn.Conv2d(hidden_size, hidden_size, kernel, (2, 2), padding),
19
- nn.LeakyReLU(0.2, inplace=True),
20
- nn.Dropout2d(0.25),
21
- nn.BatchNorm2d(hidden_size, 0.8)
22
- ]),
23
- nn.Sequential(*[
24
- nn.Conv2d(hidden_size, hidden_size, kernel, (2, 2), padding),
25
- nn.LeakyReLU(0.2, inplace=True),
26
- nn.Dropout2d(0.25),
27
- ]),
28
- ])
29
- ds_size = (time_length // 2 ** 3, (freq_length + 7) // 2 ** 3)
30
- self.adv_layer = nn.Linear(hidden_size * ds_size[0] * ds_size[1], 1)
31
-
32
- def forward(self, x):
33
- """
34
- :param x: [B, C, T, n_bins]
35
- :return: validity: [B, 1], h: List of hiddens
36
- """
37
- h = []
38
- for l in self.model:
39
- x = l(x)
40
- h.append(x)
41
- x = x.view(x.shape[0], -1)
42
- validity = self.adv_layer(x) # [B, 1]
43
- return validity, h
44
-
45
-
46
- class MultiWindowDiscriminator(nn.Module):
47
- def __init__(self, time_lengths, freq_length=80, kernel=(3, 3), c_in=1, hidden_size=128):
48
- super(MultiWindowDiscriminator, self).__init__()
49
- self.win_lengths = time_lengths
50
- self.discriminators = nn.ModuleList()
51
-
52
- for time_length in time_lengths:
53
- self.discriminators += [SingleWindowDisc(time_length, freq_length, kernel, c_in=c_in, hidden_size=hidden_size)]
54
-
55
- def forward(self, x, x_len, start_frames_wins=None):
56
- '''
57
- Args:
58
- x (tensor): input mel, (B, c_in, T, n_bins).
59
- x_length (tensor): len of per mel. (B,).
60
-
61
- Returns:
62
- tensor : (B).
63
- '''
64
- validity = []
65
- if start_frames_wins is None:
66
- start_frames_wins = [None] * len(self.discriminators)
67
- h = []
68
- for i, start_frames in zip(range(len(self.discriminators)), start_frames_wins):
69
- x_clip, start_frames = self.clip(x, x_len, self.win_lengths[i], start_frames) # (B, win_length, C)
70
- start_frames_wins[i] = start_frames
71
- if x_clip is None:
72
- continue
73
- x_clip, h_ = self.discriminators[i](x_clip)
74
- h += h_
75
- validity.append(x_clip)
76
- if len(validity) != len(self.discriminators):
77
- return None, start_frames_wins, h
78
- validity = sum(validity) # [B]
79
- return validity, start_frames_wins, h
80
-
81
- def clip(self, x, x_len, win_length, start_frames=None):
82
- '''Ramdom clip x to win_length.
83
- Args:
84
- x (tensor) : (B, c_in, T, n_bins).
85
- cond (tensor) : (B, T, H).
86
- x_len (tensor) : (B,).
87
- win_length (int): target clip length
88
-
89
- Returns:
90
- (tensor) : (B, c_in, win_length, n_bins).
91
-
92
- '''
93
- T_start = 0
94
- T_end = x_len.max() - win_length
95
- if T_end < 0:
96
- return None, None, start_frames
97
- T_end = T_end.item()
98
- if start_frames is None:
99
- start_frame = np.random.randint(low=T_start, high=T_end + 1)
100
- start_frames = [start_frame] * x.size(0)
101
- else:
102
- start_frame = start_frames[0]
103
- x_batch = x[:, :, start_frame: start_frame + win_length]
104
- return x_batch, start_frames
105
-
106
-
107
- class Discriminator(nn.Module):
108
- def __init__(self, time_lengths=[32, 64, 128], freq_length=80, kernel=(3, 3), c_in=1,
109
- hidden_size=128):
110
- super(Discriminator, self).__init__()
111
- self.time_lengths = time_lengths
112
- self.discriminator = MultiWindowDiscriminator(
113
- freq_length=freq_length,
114
- time_lengths=time_lengths,
115
- kernel=kernel,
116
- c_in=c_in, hidden_size=hidden_size
117
- )
118
-
119
-
120
- def forward(self, x, start_frames_wins=None):
121
- """
122
-
123
- :param x: [B, T, 80]
124
- :param return_y_only:
125
- :return:
126
- """
127
- if len(x.shape) == 3:
128
- x = x[:, None, :, :] # [B,1,T,80]
129
- x_len = x.sum([1, -1]).ne(0).int().sum([-1])
130
- ret = {'y_c': None, 'y': None}
131
- ret['y'], start_frames_wins, ret['h'] = self.discriminator(
132
- x, x_len, start_frames_wins=start_frames_wins)
133
-
134
- ret['start_frames_wins'] = start_frames_wins
135
- return ret
136
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AIGC-Audio/AudioGPT/text_to_speech/modules/vocoder/hifigan/mel_utils.py DELETED
@@ -1,80 +0,0 @@
1
- import numpy as np
2
- import torch
3
- import torch.utils.data
4
- from librosa.filters import mel as librosa_mel_fn
5
- from scipy.io.wavfile import read
6
-
7
- MAX_WAV_VALUE = 32768.0
8
-
9
-
10
- def load_wav(full_path):
11
- sampling_rate, data = read(full_path)
12
- return data, sampling_rate
13
-
14
-
15
- def dynamic_range_compression(x, C=1, clip_val=1e-5):
16
- return np.log(np.clip(x, a_min=clip_val, a_max=None) * C)
17
-
18
-
19
- def dynamic_range_decompression(x, C=1):
20
- return np.exp(x) / C
21
-
22
-
23
- def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
24
- return torch.log(torch.clamp(x, min=clip_val) * C)
25
-
26
-
27
- def dynamic_range_decompression_torch(x, C=1):
28
- return torch.exp(x) / C
29
-
30
-
31
- def spectral_normalize_torch(magnitudes):
32
- output = dynamic_range_compression_torch(magnitudes)
33
- return output
34
-
35
-
36
- def spectral_de_normalize_torch(magnitudes):
37
- output = dynamic_range_decompression_torch(magnitudes)
38
- return output
39
-
40
-
41
- mel_basis = {}
42
- hann_window = {}
43
-
44
-
45
- def mel_spectrogram(y, hparams, center=False, complex=False):
46
- # hop_size: 512 # For 22050Hz, 275 ~= 12.5 ms (0.0125 * sample_rate)
47
- # win_size: 2048 # For 22050Hz, 1100 ~= 50 ms (If None, win_size: fft_size) (0.05 * sample_rate)
48
- # fmin: 55 # Set this to 55 if your speaker is male! if female, 95 should help taking off noise. (To test depending on dataset. Pitch info: male~[65, 260], female~[100, 525])
49
- # fmax: 10000 # To be increased/reduced depending on data.
50
- # fft_size: 2048 # Extra window size is filled with 0 paddings to match this parameter
51
- # n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax,
52
- n_fft = hparams['fft_size']
53
- num_mels = hparams['audio_num_mel_bins']
54
- sampling_rate = hparams['audio_sample_rate']
55
- hop_size = hparams['hop_size']
56
- win_size = hparams['win_size']
57
- fmin = hparams['fmin']
58
- fmax = hparams['fmax']
59
- y = y.clamp(min=-1., max=1.)
60
- global mel_basis, hann_window
61
- if fmax not in mel_basis:
62
- mel = librosa_mel_fn(sampling_rate, n_fft, num_mels, fmin, fmax)
63
- mel_basis[str(fmax) + '_' + str(y.device)] = torch.from_numpy(mel).float().to(y.device)
64
- hann_window[str(y.device)] = torch.hann_window(win_size).to(y.device)
65
-
66
- y = torch.nn.functional.pad(y.unsqueeze(1), [int((n_fft - hop_size) / 2), int((n_fft - hop_size) / 2)],
67
- mode='reflect')
68
- y = y.squeeze(1)
69
-
70
- spec = torch.stft(y, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window[str(y.device)],
71
- center=center, pad_mode='reflect', normalized=False, onesided=True)
72
-
73
- if not complex:
74
- spec = torch.sqrt(spec.pow(2).sum(-1) + (1e-9))
75
- spec = torch.matmul(mel_basis[str(fmax) + '_' + str(y.device)], spec)
76
- spec = spectral_normalize_torch(spec)
77
- else:
78
- B, C, T, _ = spec.shape
79
- spec = spec.transpose(1, 2) # [B, T, n_fft, 2]
80
- return spec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AIGC-Audio/AudioGPT/text_to_speech/utils/commons/multiprocess_utils.py DELETED
@@ -1,130 +0,0 @@
1
- import os
2
- import traceback
3
- from functools import partial
4
- from tqdm import tqdm
5
-
6
-
7
- def chunked_worker(worker_id, args_queue=None, results_queue=None, init_ctx_func=None):
8
- ctx = init_ctx_func(worker_id) if init_ctx_func is not None else None
9
- while True:
10
- args = args_queue.get()
11
- if args == '<KILL>':
12
- return
13
- job_idx, map_func, arg = args
14
- try:
15
- map_func_ = partial(map_func, ctx=ctx) if ctx is not None else map_func
16
- if isinstance(arg, dict):
17
- res = map_func_(**arg)
18
- elif isinstance(arg, (list, tuple)):
19
- res = map_func_(*arg)
20
- else:
21
- res = map_func_(arg)
22
- results_queue.put((job_idx, res))
23
- except:
24
- traceback.print_exc()
25
- results_queue.put((job_idx, None))
26
-
27
-
28
- class MultiprocessManager:
29
- def __init__(self, num_workers=None, init_ctx_func=None, multithread=False, queue_max=-1):
30
- if multithread:
31
- from multiprocessing.dummy import Queue, Process
32
- else:
33
- from multiprocessing import Queue, Process
34
- if num_workers is None:
35
- num_workers = int(os.getenv('N_PROC', os.cpu_count()))
36
- self.num_workers = num_workers
37
- self.results_queue = Queue(maxsize=-1)
38
- self.jobs_pending = []
39
- self.args_queue = Queue(maxsize=queue_max)
40
- self.workers = []
41
- self.total_jobs = 0
42
- self.multithread = multithread
43
- for i in range(num_workers):
44
- if multithread:
45
- p = Process(target=chunked_worker,
46
- args=(i, self.args_queue, self.results_queue, init_ctx_func))
47
- else:
48
- p = Process(target=chunked_worker,
49
- args=(i, self.args_queue, self.results_queue, init_ctx_func),
50
- daemon=True)
51
- self.workers.append(p)
52
- p.start()
53
-
54
- def add_job(self, func, args):
55
- if not self.args_queue.full():
56
- self.args_queue.put((self.total_jobs, func, args))
57
- else:
58
- self.jobs_pending.append((self.total_jobs, func, args))
59
- self.total_jobs += 1
60
-
61
- def get_results(self):
62
- self.n_finished = 0
63
- while self.n_finished < self.total_jobs:
64
- while len(self.jobs_pending) > 0 and not self.args_queue.full():
65
- self.args_queue.put(self.jobs_pending[0])
66
- self.jobs_pending = self.jobs_pending[1:]
67
- job_id, res = self.results_queue.get()
68
- yield job_id, res
69
- self.n_finished += 1
70
- for w in range(self.num_workers):
71
- self.args_queue.put("<KILL>")
72
- for w in self.workers:
73
- w.join()
74
-
75
- def close(self):
76
- if not self.multithread:
77
- for w in self.workers:
78
- w.terminate()
79
-
80
- def __len__(self):
81
- return self.total_jobs
82
-
83
-
84
- def multiprocess_run_tqdm(map_func, args, num_workers=None, ordered=True, init_ctx_func=None,
85
- multithread=False, queue_max=-1, desc=None):
86
- for i, res in tqdm(
87
- multiprocess_run(map_func, args, num_workers, ordered, init_ctx_func, multithread,
88
- queue_max=queue_max),
89
- total=len(args), desc=desc):
90
- yield i, res
91
-
92
-
93
- def multiprocess_run(map_func, args, num_workers=None, ordered=True, init_ctx_func=None, multithread=False,
94
- queue_max=-1):
95
- """
96
- Multiprocessing running chunked jobs.
97
-
98
- Examples:
99
- >>> for res in tqdm(multiprocess_run(job_func, args):
100
- >>> print(res)
101
-
102
- :param map_func:
103
- :param args:
104
- :param num_workers:
105
- :param ordered:
106
- :param init_ctx_func:
107
- :param q_max_size:
108
- :param multithread:
109
- :return:
110
- """
111
- if num_workers is None:
112
- num_workers = int(os.getenv('N_PROC', os.cpu_count()))
113
- # num_workers = 1
114
- manager = MultiprocessManager(num_workers, init_ctx_func, multithread, queue_max=queue_max)
115
- for arg in args:
116
- manager.add_job(map_func, arg)
117
- if ordered:
118
- n_jobs = len(args)
119
- results = ['<WAIT>' for _ in range(n_jobs)]
120
- i_now = 0
121
- for job_i, res in manager.get_results():
122
- results[job_i] = res
123
- while i_now < n_jobs and (not isinstance(results[i_now], str) or results[i_now] != '<WAIT>'):
124
- yield i_now, results[i_now]
125
- results[i_now] = None
126
- i_now += 1
127
- else:
128
- for job_i, res in manager.get_results():
129
- yield job_i, res
130
- manager.close()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/ARTeLab/DTM_Estimation_SRandD/README.md DELETED
@@ -1,12 +0,0 @@
1
- ---
2
- title: DTM Estimation SRandD
3
- emoji: 👁
4
- colorFrom: pink
5
- colorTo: indigo
6
- sdk: gradio
7
- sdk_version: 3.0.20
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/ASJMO/freegpt/client/css/label.css DELETED
@@ -1,16 +0,0 @@
1
- label {
2
- cursor: pointer;
3
- text-indent: -9999px;
4
- width: 50px;
5
- height: 30px;
6
- backdrop-filter: blur(20px);
7
- -webkit-backdrop-filter: blur(20px);
8
- background-color: var(--blur-bg);
9
- border-radius: var(--border-radius-1);
10
- border: 1px solid var(--blur-border);
11
- display: block;
12
- border-radius: 100px;
13
- position: relative;
14
- overflow: hidden;
15
- transition: 0.33s;
16
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/ASJMO/freegpt/client/js/highlight.min.js DELETED
The diff for this file is too large to render. See raw diff
 
spaces/AchyuthGamer/OpenGPT-Chat-UI/src/lib/utils/models.ts DELETED
@@ -1,4 +0,0 @@
1
- import type { Model } from "$lib/types/Model";
2
-
3
- export const findCurrentModel = (models: Model[], id?: string) =>
4
- models.find((m) => m.id === id) ?? models[0];
 
 
 
 
 
spaces/AgentVerse/agentVerse/agentverse/agents/tasksolving_agent/evaluator.py DELETED
@@ -1,86 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import asyncio
4
- from colorama import Fore
5
-
6
- from agentverse.logging import get_logger
7
- import bdb
8
- from string import Template
9
- from typing import TYPE_CHECKING, List, Tuple
10
-
11
- from agentverse.message import EvaluatorMessage, Message
12
-
13
- from agentverse.agents import agent_registry
14
- from agentverse.agents.base import BaseAgent
15
-
16
-
17
- logger = get_logger()
18
-
19
-
20
- @agent_registry.register("evaluator")
21
- class EvaluatorAgent(BaseAgent):
22
- def step(
23
- self,
24
- solution: str,
25
- result: str,
26
- task_description: str,
27
- all_role_description: str,
28
- ) -> EvaluatorMessage:
29
- logger.debug("", self.name, Fore.MAGENTA)
30
- prepend_prompt, append_prompt = self.get_all_prompts(
31
- solution=solution,
32
- result=result,
33
- task_description=task_description,
34
- all_role_description=all_role_description,
35
- )
36
- history = self.memory.to_messages(self.name)
37
- parsed_response = None
38
- for i in range(self.max_retry):
39
- try:
40
- response = self.llm.generate_response(
41
- prepend_prompt, history, append_prompt
42
- )
43
- parsed_response = self.output_parser.parse(response)
44
- break
45
- except (KeyboardInterrupt, bdb.BdbQuit):
46
- raise
47
- except Exception as e:
48
- logger.error(e)
49
- logger.warn("Retrying...")
50
- continue
51
-
52
- if parsed_response is None:
53
- logger.error(f"{self.name} failed to generate valid response.")
54
- message = EvaluatorMessage(
55
- sender=self.name,
56
- sender_agent=self,
57
- score=parsed_response[0] if parsed_response is not None else 0,
58
- advice=parsed_response[1] if parsed_response is not None else "",
59
- )
60
- return message
61
- # return parsed_response
62
-
63
- async def astep(self, solution: str) -> EvaluatorMessage:
64
- """Asynchronous version of step"""
65
- pass
66
-
67
- def _fill_prompt_template(self, solution: str, task_description: str) -> str:
68
- """Fill the placeholders in the prompt template
69
-
70
- In the role_assigner agent, three placeholders are supported:
71
- - ${task_description}
72
- - ${solution}
73
- """
74
- input_arguments = {
75
- "task_description": task_description,
76
- "solution": solution,
77
- }
78
- return Template(self.prompt_template).safe_substitute(input_arguments)
79
-
80
- def add_message_to_memory(self, messages: List[Message]) -> None:
81
- self.memory.add_message(messages)
82
-
83
- def reset(self) -> None:
84
- """Reset the agent"""
85
- self.memory.reset()
86
- # TODO: reset receiver
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AlexWang/lama/fetch_data/places_standard_train_prepare.sh DELETED
@@ -1,16 +0,0 @@
1
- mkdir -p places_standard_dataset/train
2
-
3
- # untar without folder structure
4
- tar -xvf train_large_places365standard.tar --transform='s/.*\///' -C places_standard_dataset/train
5
-
6
- # create location config places.yaml
7
- PWD=$(pwd)
8
- DATASET=${PWD}/places_standard_dataset
9
- PLACES=${PWD}/configs/training/location/places_standard.yaml
10
-
11
- touch $PLACES
12
- echo "# @package _group_" >> $PLACES
13
- echo "data_root_dir: ${DATASET}/" >> $PLACES
14
- echo "out_root_dir: ${PWD}/experiments/" >> $PLACES
15
- echo "tb_dir: ${PWD}/tb_logs/" >> $PLACES
16
- echo "pretrained_models: ${PWD}/" >> $PLACES
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Aloento/9Nine-PITS/text/frontend/zh_normalization/num.py DELETED
@@ -1,238 +0,0 @@
1
- # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- """
15
- Rules to verbalize numbers into Chinese characters.
16
- https://zh.wikipedia.org/wiki/中文数字#現代中文
17
- """
18
- import re
19
- from collections import OrderedDict
20
- from typing import List
21
-
22
- DIGITS = {str(i): tran for i, tran in enumerate('零一二三四五六七八九')}
23
- UNITS = OrderedDict({
24
- 1: '十',
25
- 2: '百',
26
- 3: '千',
27
- 4: '万',
28
- 8: '亿',
29
- })
30
-
31
- COM_QUANTIFIERS = '(所|朵|匹|张|座|回|场|尾|条|个|首|阙|阵|网|炮|顶|丘|棵|只|支|袭|辆|挑|担|颗|壳|窠|曲|墙|群|腔|砣|座|客|贯|扎|捆|刀|令|打|手|罗|坡|山|岭|江|溪|钟|队|单|双|对|出|口|头|脚|板|跳|枝|件|贴|针|线|管|名|位|身|堂|课|本|页|家|户|层|丝|毫|厘|分|钱|两|斤|担|铢|石|钧|锱|忽|(千|毫|微)克|毫|厘|(公)分|分|寸|尺|丈|里|寻|常|铺|程|(千|分|厘|毫|微)米|米|撮|勺|合|升|斗|石|盘|碗|碟|叠|桶|笼|盆|盒|杯|钟|斛|锅|簋|篮|盘|桶|罐|瓶|壶|卮|盏|箩|箱|煲|啖|袋|钵|年|月|日|季|刻|时|周|天|秒|分|小时|旬|纪|岁|世|更|夜|春|夏|秋|冬|代|伏|辈|丸|泡|粒|颗|幢|堆|条|根|支|道|面|片|张|颗|块|元|(亿|千万|百万|万|千|百)|(亿|千万|百万|万|千|百|美|)元|(亿|千万|百万|万|千|百|)块|角|毛|分)'
32
-
33
- # 分数表达式
34
- RE_FRAC = re.compile(r'(-?)(\d+)/(\d+)')
35
-
36
-
37
- def replace_frac(match) -> str:
38
- """
39
- Args:
40
- match (re.Match)
41
- Returns:
42
- str
43
- """
44
- sign = match.group(1)
45
- nominator = match.group(2)
46
- denominator = match.group(3)
47
- sign: str = "负" if sign else ""
48
- nominator: str = num2str(nominator)
49
- denominator: str = num2str(denominator)
50
- result = f"{sign}{denominator}分之{nominator}"
51
- return result
52
-
53
-
54
- # 百分数表达式
55
- RE_PERCENTAGE = re.compile(r'(-?)(\d+(\.\d+)?)%')
56
-
57
-
58
- def replace_percentage(match) -> str:
59
- """
60
- Args:
61
- match (re.Match)
62
- Returns:
63
- str
64
- """
65
- sign = match.group(1)
66
- percent = match.group(2)
67
- sign: str = "负" if sign else ""
68
- percent: str = num2str(percent)
69
- result = f"{sign}百分之{percent}"
70
- return result
71
-
72
-
73
- # 整数表达式
74
- # 带负号的整数 -10
75
- RE_INTEGER = re.compile(r'(-)' r'(\d+)')
76
-
77
-
78
- def replace_negative_num(match) -> str:
79
- """
80
- Args:
81
- match (re.Match)
82
- Returns:
83
- str
84
- """
85
- sign = match.group(1)
86
- number = match.group(2)
87
- sign: str = "负" if sign else ""
88
- number: str = num2str(number)
89
- result = f"{sign}{number}"
90
- return result
91
-
92
-
93
- # 编号-无符号整形
94
- # 00078
95
- RE_DEFAULT_NUM = re.compile(r'\d{3}\d*')
96
-
97
-
98
- def replace_default_num(match):
99
- """
100
- Args:
101
- match (re.Match)
102
- Returns:
103
- str
104
- """
105
- number = match.group(0)
106
- return verbalize_digit(number)
107
-
108
-
109
- # 数字表达式
110
- # 纯小数
111
- RE_DECIMAL_NUM = re.compile(r'(-?)((\d+)(\.\d+))' r'|(\.(\d+))')
112
- # 正整数 + 量词
113
- RE_POSITIVE_QUANTIFIERS = re.compile(r"(\d+)([多余几\+])?" + COM_QUANTIFIERS)
114
- RE_NUMBER = re.compile(r'(-?)((\d+)(\.\d+)?)' r'|(\.(\d+))')
115
-
116
-
117
- def replace_positive_quantifier(match) -> str:
118
- """
119
- Args:
120
- match (re.Match)
121
- Returns:
122
- str
123
- """
124
- number = match.group(1)
125
- match_2 = match.group(2)
126
- if match_2 == "+":
127
- match_2 = "多"
128
- match_2: str = match_2 if match_2 else ""
129
- quantifiers: str = match.group(3)
130
- number: str = num2str(number)
131
- result = f"{number}{match_2}{quantifiers}"
132
- return result
133
-
134
-
135
- def replace_number(match) -> str:
136
- """
137
- Args:
138
- match (re.Match)
139
- Returns:
140
- str
141
- """
142
- sign = match.group(1)
143
- number = match.group(2)
144
- pure_decimal = match.group(5)
145
- if pure_decimal:
146
- result = num2str(pure_decimal)
147
- else:
148
- sign: str = "负" if sign else ""
149
- number: str = num2str(number)
150
- result = f"{sign}{number}"
151
- return result
152
-
153
-
154
- # 范围表达式
155
- # match.group(1) and match.group(8) are copy from RE_NUMBER
156
-
157
- RE_RANGE = re.compile(
158
- r'((-?)((\d+)(\.\d+)?)|(\.(\d+)))[-~]((-?)((\d+)(\.\d+)?)|(\.(\d+)))')
159
-
160
-
161
- def replace_range(match) -> str:
162
- """
163
- Args:
164
- match (re.Match)
165
- Returns:
166
- str
167
- """
168
- first, second = match.group(1), match.group(8)
169
- first = RE_NUMBER.sub(replace_number, first)
170
- second = RE_NUMBER.sub(replace_number, second)
171
- result = f"{first}到{second}"
172
- return result
173
-
174
-
175
- def _get_value(value_string: str, use_zero: bool = True) -> List[str]:
176
- stripped = value_string.lstrip('0')
177
- if len(stripped) == 0:
178
- return []
179
- elif len(stripped) == 1:
180
- if use_zero and len(stripped) < len(value_string):
181
- return [DIGITS['0'], DIGITS[stripped]]
182
- else:
183
- return [DIGITS[stripped]]
184
- else:
185
- largest_unit = next(
186
- power for power in reversed(UNITS.keys()) if power < len(stripped))
187
- first_part = value_string[:-largest_unit]
188
- second_part = value_string[-largest_unit:]
189
- return _get_value(first_part) + [UNITS[largest_unit]] + _get_value(
190
- second_part)
191
-
192
-
193
- def verbalize_cardinal(value_string: str) -> str:
194
- if not value_string:
195
- return ''
196
-
197
- # 000 -> '零' , 0 -> '零'
198
- value_string = value_string.lstrip('0')
199
- if len(value_string) == 0:
200
- return DIGITS['0']
201
-
202
- result_symbols = _get_value(value_string)
203
- # verbalized number starting with '一十*' is abbreviated as `十*`
204
- if len(result_symbols) >= 2 and result_symbols[0] == DIGITS[
205
- '1'] and result_symbols[1] == UNITS[1]:
206
- result_symbols = result_symbols[1:]
207
- return ''.join(result_symbols)
208
-
209
-
210
- def verbalize_digit(value_string: str, alt_one=False) -> str:
211
- result_symbols = [DIGITS[digit] for digit in value_string]
212
- result = ''.join(result_symbols)
213
- if alt_one:
214
- result = result.replace("一", "幺")
215
- return result
216
-
217
-
218
- def num2str(value_string: str) -> str:
219
- integer_decimal = value_string.split('.')
220
- if len(integer_decimal) == 1:
221
- integer = integer_decimal[0]
222
- decimal = ''
223
- elif len(integer_decimal) == 2:
224
- integer, decimal = integer_decimal
225
- else:
226
- raise ValueError(
227
- f"The value string: '${value_string}' has more than one point in it."
228
- )
229
-
230
- result = verbalize_cardinal(integer)
231
-
232
- decimal = decimal.rstrip('0')
233
- if decimal:
234
- # '.22' is verbalized as '零点二二'
235
- # '3.20' is verbalized as '三点二
236
- result = result if result else "零"
237
- result += '点' + verbalize_digit(decimal)
238
- return result
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Amrrs/DragGan-Inversion/torch_utils/misc.py DELETED
@@ -1,295 +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
- import re
10
- import contextlib
11
- import numpy as np
12
- import torch
13
- import warnings
14
- import dnnlib
15
-
16
- # ----------------------------------------------------------------------------
17
- # Cached construction of constant tensors. Avoids CPU=>GPU copy when the
18
- # same constant is used multiple times.
19
-
20
- _constant_cache = dict()
21
-
22
-
23
- def constant(value, shape=None, dtype=None, device=None, memory_format=None):
24
- value = np.asarray(value)
25
- if shape is not None:
26
- shape = tuple(shape)
27
- if dtype is None:
28
- dtype = torch.get_default_dtype()
29
- if device is None:
30
- device = torch.device('cpu')
31
- if memory_format is None:
32
- memory_format = torch.contiguous_format
33
-
34
- key = (value.shape, value.dtype, value.tobytes(),
35
- shape, dtype, device, memory_format)
36
- tensor = _constant_cache.get(key, None)
37
- if tensor is None:
38
- tensor = torch.as_tensor(value.copy(), dtype=dtype, device=device)
39
- if shape is not None:
40
- tensor, _ = torch.broadcast_tensors(tensor, torch.empty(shape))
41
- tensor = tensor.contiguous(memory_format=memory_format)
42
- _constant_cache[key] = tensor
43
- return tensor
44
-
45
- # ----------------------------------------------------------------------------
46
- # Replace NaN/Inf with specified numerical values.
47
-
48
-
49
- try:
50
- nan_to_num = torch.nan_to_num # 1.8.0a0
51
- except AttributeError:
52
- def nan_to_num(input, nan=0.0, posinf=None, neginf=None, *, out=None): # pylint: disable=redefined-builtin
53
- assert isinstance(input, torch.Tensor)
54
- if posinf is None:
55
- posinf = torch.finfo(input.dtype).max
56
- if neginf is None:
57
- neginf = torch.finfo(input.dtype).min
58
- assert nan == 0
59
- return torch.clamp(input.unsqueeze(0).nansum(0), min=neginf, max=posinf, out=out)
60
-
61
- # ----------------------------------------------------------------------------
62
- # Symbolic assert.
63
-
64
- try:
65
- symbolic_assert = torch._assert # 1.8.0a0 # pylint: disable=protected-access
66
- except AttributeError:
67
- symbolic_assert = torch.Assert # 1.7.0
68
-
69
- # ----------------------------------------------------------------------------
70
- # Context manager to temporarily suppress known warnings in torch.jit.trace().
71
- # Note: Cannot use catch_warnings because of https://bugs.python.org/issue29672
72
-
73
-
74
- @contextlib.contextmanager
75
- def suppress_tracer_warnings():
76
- flt = ('ignore', None, torch.jit.TracerWarning, None, 0)
77
- warnings.filters.insert(0, flt)
78
- yield
79
- warnings.filters.remove(flt)
80
-
81
- # ----------------------------------------------------------------------------
82
- # Assert that the shape of a tensor matches the given list of integers.
83
- # None indicates that the size of a dimension is allowed to vary.
84
- # Performs symbolic assertion when used in torch.jit.trace().
85
-
86
-
87
- def assert_shape(tensor, ref_shape):
88
- if tensor.ndim != len(ref_shape):
89
- raise AssertionError(
90
- f'Wrong number of dimensions: got {tensor.ndim}, expected {len(ref_shape)}')
91
- for idx, (size, ref_size) in enumerate(zip(tensor.shape, ref_shape)):
92
- if ref_size is None:
93
- pass
94
- elif isinstance(ref_size, torch.Tensor):
95
- with suppress_tracer_warnings(): # as_tensor results are registered as constants
96
- symbolic_assert(torch.equal(torch.as_tensor(
97
- size), ref_size), f'Wrong size for dimension {idx}')
98
- elif isinstance(size, torch.Tensor):
99
- with suppress_tracer_warnings(): # as_tensor results are registered as constants
100
- symbolic_assert(torch.equal(size, torch.as_tensor(
101
- ref_size)), f'Wrong size for dimension {idx}: expected {ref_size}')
102
- elif size != ref_size:
103
- raise AssertionError(
104
- f'Wrong size for dimension {idx}: got {size}, expected {ref_size}')
105
-
106
- # ----------------------------------------------------------------------------
107
- # Function decorator that calls torch.autograd.profiler.record_function().
108
-
109
-
110
- def profiled_function(fn):
111
- def decorator(*args, **kwargs):
112
- with torch.autograd.profiler.record_function(fn.__name__):
113
- return fn(*args, **kwargs)
114
- decorator.__name__ = fn.__name__
115
- return decorator
116
-
117
- # ----------------------------------------------------------------------------
118
- # Sampler for torch.utils.data.DataLoader that loops over the dataset
119
- # indefinitely, shuffling items as it goes.
120
-
121
-
122
- class InfiniteSampler(torch.utils.data.Sampler):
123
- def __init__(self, dataset, rank=0, num_replicas=1, shuffle=True, seed=0, window_size=0.5):
124
- assert len(dataset) > 0
125
- assert num_replicas > 0
126
- assert 0 <= rank < num_replicas
127
- assert 0 <= window_size <= 1
128
- super().__init__(dataset)
129
- self.dataset = dataset
130
- self.rank = rank
131
- self.num_replicas = num_replicas
132
- self.shuffle = shuffle
133
- self.seed = seed
134
- self.window_size = window_size
135
-
136
- def __iter__(self):
137
- order = np.arange(len(self.dataset))
138
- rnd = None
139
- window = 0
140
- if self.shuffle:
141
- rnd = np.random.RandomState(self.seed)
142
- rnd.shuffle(order)
143
- window = int(np.rint(order.size * self.window_size))
144
-
145
- idx = 0
146
- while True:
147
- i = idx % order.size
148
- if idx % self.num_replicas == self.rank:
149
- yield order[i]
150
- if window >= 2:
151
- j = (i - rnd.randint(window)) % order.size
152
- order[i], order[j] = order[j], order[i]
153
- idx += 1
154
-
155
- # ----------------------------------------------------------------------------
156
- # Utilities for operating with torch.nn.Module parameters and buffers.
157
-
158
-
159
- def params_and_buffers(module):
160
- assert isinstance(module, torch.nn.Module)
161
- return list(module.parameters()) + list(module.buffers())
162
-
163
-
164
- def named_params_and_buffers(module):
165
- assert isinstance(module, torch.nn.Module)
166
- return list(module.named_parameters()) + list(module.named_buffers())
167
-
168
-
169
- def copy_params_and_buffers(src_module, dst_module, require_all=False):
170
- assert isinstance(src_module, torch.nn.Module)
171
- assert isinstance(dst_module, torch.nn.Module)
172
- src_tensors = dict(named_params_and_buffers(src_module))
173
- for name, tensor in named_params_and_buffers(dst_module):
174
- assert (name in src_tensors) or (not require_all)
175
- if name in src_tensors:
176
- tensor.copy_(src_tensors[name].detach()).requires_grad_(
177
- tensor.requires_grad)
178
-
179
- # ----------------------------------------------------------------------------
180
- # Context manager for easily enabling/disabling DistributedDataParallel
181
- # synchronization.
182
-
183
-
184
- @contextlib.contextmanager
185
- def ddp_sync(module, sync):
186
- assert isinstance(module, torch.nn.Module)
187
- if sync or not isinstance(module, torch.nn.parallel.DistributedDataParallel):
188
- yield
189
- else:
190
- with module.no_sync():
191
- yield
192
-
193
- # ----------------------------------------------------------------------------
194
- # Check DistributedDataParallel consistency across processes.
195
-
196
-
197
- def check_ddp_consistency(module, ignore_regex=None):
198
- assert isinstance(module, torch.nn.Module)
199
- for name, tensor in named_params_and_buffers(module):
200
- fullname = type(module).__name__ + '.' + name
201
- if ignore_regex is not None and re.fullmatch(ignore_regex, fullname):
202
- continue
203
- tensor = tensor.detach()
204
- if tensor.is_floating_point():
205
- tensor = nan_to_num(tensor)
206
- other = tensor.clone()
207
- torch.distributed.broadcast(tensor=other, src=0)
208
- assert (tensor == other).all(), fullname
209
-
210
- # ----------------------------------------------------------------------------
211
- # Print summary table of module hierarchy.
212
-
213
-
214
- def print_module_summary(module, inputs, max_nesting=3, skip_redundant=True):
215
- assert isinstance(module, torch.nn.Module)
216
- assert not isinstance(module, torch.jit.ScriptModule)
217
- assert isinstance(inputs, (tuple, list))
218
-
219
- # Register hooks.
220
- entries = []
221
- nesting = [0]
222
-
223
- def pre_hook(_mod, _inputs):
224
- nesting[0] += 1
225
-
226
- def post_hook(mod, _inputs, outputs):
227
- nesting[0] -= 1
228
- if nesting[0] <= max_nesting:
229
- outputs = list(outputs) if isinstance(
230
- outputs, (tuple, list)) else [outputs]
231
- outputs = [t for t in outputs if isinstance(t, torch.Tensor)]
232
- entries.append(dnnlib.EasyDict(mod=mod, outputs=outputs))
233
- hooks = [mod.register_forward_pre_hook(
234
- pre_hook) for mod in module.modules()]
235
- hooks += [mod.register_forward_hook(post_hook) for mod in module.modules()]
236
-
237
- # Run module.
238
- outputs = module(*inputs)
239
- for hook in hooks:
240
- hook.remove()
241
-
242
- # Identify unique outputs, parameters, and buffers.
243
- tensors_seen = set()
244
- for e in entries:
245
- e.unique_params = [
246
- t for t in e.mod.parameters() if id(t) not in tensors_seen]
247
- e.unique_buffers = [
248
- t for t in e.mod.buffers() if id(t) not in tensors_seen]
249
- e.unique_outputs = [t for t in e.outputs if id(t) not in tensors_seen]
250
- tensors_seen |= {id(t) for t in e.unique_params +
251
- e.unique_buffers + e.unique_outputs}
252
-
253
- # Filter out redundant entries.
254
- if skip_redundant:
255
- entries = [e for e in entries if len(e.unique_params) or len(
256
- e.unique_buffers) or len(e.unique_outputs)]
257
-
258
- # Construct table.
259
- rows = [[type(module).__name__, 'Parameters',
260
- 'Buffers', 'Output shape', 'Datatype']]
261
- rows += [['---'] * len(rows[0])]
262
- param_total = 0
263
- buffer_total = 0
264
- submodule_names = {mod: name for name, mod in module.named_modules()}
265
- for e in entries:
266
- name = '<top-level>' if e.mod is module else submodule_names[e.mod]
267
- param_size = sum(t.numel() for t in e.unique_params)
268
- buffer_size = sum(t.numel() for t in e.unique_buffers)
269
- output_shapes = [str(list(t.shape)) for t in e.outputs]
270
- output_dtypes = [str(t.dtype).split('.')[-1] for t in e.outputs]
271
- rows += [[
272
- name + (':0' if len(e.outputs) >= 2 else ''),
273
- str(param_size) if param_size else '-',
274
- str(buffer_size) if buffer_size else '-',
275
- (output_shapes + ['-'])[0],
276
- (output_dtypes + ['-'])[0],
277
- ]]
278
- for idx in range(1, len(e.outputs)):
279
- rows += [[name + f':{idx}', '-', '-',
280
- output_shapes[idx], output_dtypes[idx]]]
281
- param_total += param_size
282
- buffer_total += buffer_size
283
- rows += [['---'] * len(rows[0])]
284
- rows += [['Total', str(param_total), str(buffer_total), '-', '-']]
285
-
286
- # Print table.
287
- widths = [max(len(cell) for cell in column) for column in zip(*rows)]
288
- print()
289
- for row in rows:
290
- print(' '.join(cell + ' ' * (width - len(cell))
291
- for cell, width in zip(row, widths)))
292
- print()
293
- return outputs
294
-
295
- # ----------------------------------------------------------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Amrrs/DragGan-Inversion/visualizer_drag_gradio.py DELETED
@@ -1,934 +0,0 @@
1
- # https://huggingface.co/DragGan/DragGan-Models
2
- # https://arxiv.org/abs/2305.10973
3
- import os
4
- import os.path as osp
5
- from argparse import ArgumentParser
6
- from functools import partial
7
- from pathlib import Path
8
- import time
9
-
10
- import psutil
11
-
12
- import gradio as gr
13
- import numpy as np
14
- import torch
15
- from PIL import Image
16
-
17
- import dnnlib
18
- from gradio_utils import (ImageMask, draw_mask_on_image, draw_points_on_image,
19
- get_latest_points_pair, get_valid_mask,
20
- on_change_single_global_state)
21
- from viz.renderer import Renderer, add_watermark_np
22
-
23
-
24
- # download models from Hugging Face hub
25
- from huggingface_hub import snapshot_download
26
-
27
- model_dir = Path('./checkpoints')
28
- snapshot_download('DragGan/DragGan-Models',
29
- repo_type='model', local_dir=model_dir)
30
-
31
- cache_dir = model_dir
32
-
33
- device = 'cuda'
34
- IS_SPACE = "DragGan/DragGan" in os.environ.get('SPACE_ID', '')
35
- TIMEOUT = 80
36
-
37
-
38
- def reverse_point_pairs(points):
39
- new_points = []
40
- for p in points:
41
- new_points.append([p[1], p[0]])
42
- return new_points
43
-
44
-
45
- def clear_state(global_state, target=None):
46
- """Clear target history state from global_state
47
- If target is not defined, points and mask will be both removed.
48
- 1. set global_state['points'] as empty dict
49
- 2. set global_state['mask'] as full-one mask.
50
- """
51
- if target is None:
52
- target = ['point', 'mask']
53
- if not isinstance(target, list):
54
- target = [target]
55
- if 'point' in target:
56
- global_state['points'] = dict()
57
- print('Clear Points State!')
58
- if 'mask' in target:
59
- image_raw = global_state["images"]["image_raw"]
60
- global_state['mask'] = np.ones((image_raw.size[1], image_raw.size[0]),
61
- dtype=np.uint8)
62
- print('Clear mask State!')
63
-
64
- return global_state
65
-
66
-
67
- def init_images(global_state):
68
- """This function is called only ones with Gradio App is started.
69
- 0. pre-process global_state, unpack value from global_state of need
70
- 1. Re-init renderer
71
- 2. run `renderer._render_drag_impl` with `is_drag=False` to generate
72
- new image
73
- 3. Assign images to global state and re-generate mask
74
- """
75
-
76
- if isinstance(global_state, gr.State):
77
- state = global_state.value
78
- else:
79
- state = global_state
80
-
81
- state['renderer'].init_network(
82
- state['generator_params'], # res
83
- valid_checkpoints_dict[state['pretrained_weight']], # pkl
84
- state['params']['seed'], # w0_seed,
85
- None, # w_load
86
- state['params']['latent_space'] == 'w+', # w_plus
87
- 'const',
88
- state['params']['trunc_psi'], # trunc_psi,
89
- state['params']['trunc_cutoff'], # trunc_cutoff,
90
- None, # input_transform
91
- state['params']['lr'] # lr,
92
- )
93
-
94
- state['renderer']._render_drag_impl(state['generator_params'],
95
- is_drag=False,
96
- to_pil=True)
97
-
98
- init_image = state['generator_params'].image
99
- state['images']['image_orig'] = init_image
100
- state['images']['image_raw'] = init_image
101
- state['images']['image_show'] = Image.fromarray(
102
- add_watermark_np(np.array(init_image)))
103
- state['mask'] = np.ones((init_image.size[1], init_image.size[0]),
104
- dtype=np.uint8)
105
- return global_state
106
-
107
-
108
- def update_image_draw(image, points, mask, show_mask, global_state=None):
109
-
110
- image_draw = draw_points_on_image(image, points)
111
- if show_mask and mask is not None and not (mask == 0).all() and not (
112
- mask == 1).all():
113
- image_draw = draw_mask_on_image(image_draw, mask)
114
-
115
- image_draw = Image.fromarray(add_watermark_np(np.array(image_draw)))
116
- if global_state is not None:
117
- global_state['images']['image_show'] = image_draw
118
- return image_draw
119
-
120
-
121
- def preprocess_mask_info(global_state, image):
122
- """Function to handle mask information.
123
- 1. last_mask is None: Do not need to change mask, return mask
124
- 2. last_mask is not None:
125
- 2.1 global_state is remove_mask:
126
- 2.2 global_state is add_mask:
127
- """
128
- if isinstance(image, dict):
129
- last_mask = get_valid_mask(image['mask'])
130
- else:
131
- last_mask = None
132
- mask = global_state['mask']
133
-
134
- # mask in global state is a placeholder with all 1.
135
- if (mask == 1).all():
136
- mask = last_mask
137
-
138
- # last_mask = global_state['last_mask']
139
- editing_mode = global_state['editing_state']
140
-
141
- if last_mask is None:
142
- return global_state
143
-
144
- if editing_mode == 'remove_mask':
145
- updated_mask = np.clip(mask - last_mask, 0, 1)
146
- print(f'Last editing_state is {editing_mode}, do remove.')
147
- elif editing_mode == 'add_mask':
148
- updated_mask = np.clip(mask + last_mask, 0, 1)
149
- print(f'Last editing_state is {editing_mode}, do add.')
150
- else:
151
- updated_mask = mask
152
- print(f'Last editing_state is {editing_mode}, '
153
- 'do nothing to mask.')
154
-
155
- global_state['mask'] = updated_mask
156
- # global_state['last_mask'] = None # clear buffer
157
- return global_state
158
-
159
-
160
- def print_memory_usage():
161
- # Print system memory usage
162
- print(f"System memory usage: {psutil.virtual_memory().percent}%")
163
-
164
- # Print GPU memory usage
165
- if torch.cuda.is_available():
166
- device = torch.device("cuda")
167
- print(f"GPU memory usage: {torch.cuda.memory_allocated() / 1e9} GB")
168
- print(
169
- f"Max GPU memory usage: {torch.cuda.max_memory_allocated() / 1e9} GB")
170
- device_properties = torch.cuda.get_device_properties(device)
171
- available_memory = device_properties.total_memory - \
172
- torch.cuda.max_memory_allocated()
173
- print(f"Available GPU memory: {available_memory / 1e9} GB")
174
- else:
175
- print("No GPU available")
176
-
177
-
178
- # filter large models running on SPACES
179
- allowed_checkpoints = [] # all checkpoints
180
- if IS_SPACE:
181
- allowed_checkpoints = ["stylegan_human_v2_512.pkl",
182
- "stylegan2_dogs_1024_pytorch.pkl"]
183
-
184
- valid_checkpoints_dict = {
185
- f.name.split('.')[0]: str(f)
186
- for f in Path(cache_dir).glob('*.pkl')
187
- if f.name in allowed_checkpoints or not IS_SPACE
188
- }
189
- print('Valid checkpoint file:')
190
- print(valid_checkpoints_dict)
191
-
192
- init_pkl = 'stylegan_human_v2_512'
193
-
194
- with gr.Blocks() as app:
195
- gr.Markdown("""
196
- # DragGAN - Drag Your GAN
197
- ## Interactive Point-based Manipulation on the Generative Image Manifold
198
- ### Unofficial Gradio Demo
199
-
200
- **Due to high demand, only one model can be run at a time, or you can duplicate the space and run your own copy.**
201
-
202
- <a href="https://huggingface.co/spaces/radames/DragGan?duplicate=true" style="display: inline-block;margin-top: .5em;margin-right: .25em;" target="_blank">
203
- <img style="margin-bottom: 0em;display: inline;margin-top: -.25em;" src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a> for no queue on your own hardware.</p>
204
-
205
- * Official Repo: [XingangPan](https://github.com/XingangPan/DragGAN)
206
- * Gradio Demo by: [LeoXing1996](https://github.com/LeoXing1996) © [OpenMMLab MMagic](https://github.com/open-mmlab/mmagic)
207
- """)
208
-
209
- # renderer = Renderer()
210
- global_state = gr.State({
211
- "images": {
212
- # image_orig: the original image, change with seed/model is changed
213
- # image_raw: image with mask and points, change durning optimization
214
- # image_show: image showed on screen
215
- },
216
- "temporal_params": {
217
- # stop
218
- },
219
- 'mask':
220
- None, # mask for visualization, 1 for editing and 0 for unchange
221
- 'last_mask': None, # last edited mask
222
- 'show_mask': True, # add button
223
- "generator_params": dnnlib.EasyDict(),
224
- "params": {
225
- "seed": int(np.random.randint(0, 2**32 - 1)),
226
- "motion_lambda": 20,
227
- "r1_in_pixels": 3,
228
- "r2_in_pixels": 12,
229
- "magnitude_direction_in_pixels": 1.0,
230
- "latent_space": "w+",
231
- "trunc_psi": 0.7,
232
- "trunc_cutoff": None,
233
- "lr": 0.001,
234
- },
235
- "device": device,
236
- "draw_interval": 1,
237
- "renderer": Renderer(disable_timing=True),
238
- "points": {},
239
- "curr_point": None,
240
- "curr_type_point": "start",
241
- 'editing_state': 'add_points',
242
- 'pretrained_weight': init_pkl
243
- })
244
-
245
- # init image
246
- global_state = init_images(global_state)
247
- with gr.Row():
248
-
249
- with gr.Row():
250
-
251
- # Left --> tools
252
- with gr.Column(scale=3):
253
-
254
- # Pickle
255
- with gr.Row():
256
-
257
- with gr.Column(scale=1, min_width=10):
258
- gr.Markdown(value='Pickle', show_label=False)
259
-
260
- with gr.Column(scale=4, min_width=10):
261
- form_pretrained_dropdown = gr.Dropdown(
262
- choices=list(valid_checkpoints_dict.keys()),
263
- label="Pretrained Model",
264
- value=init_pkl,
265
- )
266
-
267
- # Latent
268
- with gr.Row():
269
- with gr.Column(scale=1, min_width=10):
270
- gr.Markdown(value='Latent', show_label=False)
271
-
272
- with gr.Column(scale=4, min_width=10):
273
- form_seed_number = gr.Slider(
274
- mininium=0,
275
- maximum=2**32-1,
276
- step=1,
277
- value=global_state.value['params']['seed'],
278
- interactive=True,
279
- # randomize=True,
280
- label="Seed",
281
- )
282
- form_lr_number = gr.Number(
283
- value=global_state.value["params"]["lr"],
284
- interactive=True,
285
- label="Step Size")
286
-
287
- with gr.Row():
288
- with gr.Column(scale=2, min_width=10):
289
- form_reset_image = gr.Button("Reset Image")
290
- with gr.Column(scale=3, min_width=10):
291
- form_latent_space = gr.Radio(
292
- ['w', 'w+'],
293
- value=global_state.value['params']
294
- ['latent_space'],
295
- interactive=True,
296
- label='Latent space to optimize',
297
- show_label=False,
298
- )
299
-
300
- # Drag
301
- with gr.Row():
302
- with gr.Column(scale=1, min_width=10):
303
- gr.Markdown(value='Drag', show_label=False)
304
- with gr.Column(scale=4, min_width=10):
305
- with gr.Row():
306
- with gr.Column(scale=1, min_width=10):
307
- enable_add_points = gr.Button('Add Points')
308
- with gr.Column(scale=1, min_width=10):
309
- undo_points = gr.Button('Reset Points')
310
- with gr.Row():
311
- with gr.Column(scale=1, min_width=10):
312
- form_start_btn = gr.Button("Start")
313
- with gr.Column(scale=1, min_width=10):
314
- form_stop_btn = gr.Button("Stop")
315
-
316
- form_steps_number = gr.Number(value=0,
317
- label="Steps",
318
- interactive=False)
319
-
320
- # Mask
321
- with gr.Row():
322
- with gr.Column(scale=1, min_width=10):
323
- gr.Markdown(value='Mask', show_label=False)
324
- with gr.Column(scale=4, min_width=10):
325
- enable_add_mask = gr.Button('Edit Flexible Area')
326
- with gr.Row():
327
- with gr.Column(scale=1, min_width=10):
328
- form_reset_mask_btn = gr.Button("Reset mask")
329
- with gr.Column(scale=1, min_width=10):
330
- show_mask = gr.Checkbox(
331
- label='Show Mask',
332
- value=global_state.value['show_mask'],
333
- show_label=False)
334
-
335
- with gr.Row():
336
- form_lambda_number = gr.Number(
337
- value=global_state.value["params"]
338
- ["motion_lambda"],
339
- interactive=True,
340
- label="Lambda",
341
- )
342
-
343
- form_draw_interval_number = gr.Number(
344
- value=global_state.value["draw_interval"],
345
- label="Draw Interval (steps)",
346
- interactive=True,
347
- visible=False)
348
-
349
- # Right --> Image
350
- with gr.Column(scale=8):
351
- form_image = ImageMask(
352
- value=global_state.value['images']['image_show'],
353
- brush_radius=20).style(
354
- width=768,
355
- height=768) # NOTE: hard image size code here.
356
- gr.Markdown("""
357
- ## Quick Start
358
-
359
- 1. Select desired `Pretrained Model` and adjust `Seed` to generate an
360
- initial image.
361
- 2. Click on image to add control points.
362
- 3. Click `Start` and enjoy it!
363
-
364
- ## Advance Usage
365
-
366
- 1. Change `Step Size` to adjust learning rate in drag optimization.
367
- 2. Select `w` or `w+` to change latent space to optimize:
368
- * Optimize on `w` space may cause greater influence to the image.
369
- * Optimize on `w+` space may work slower than `w`, but usually achieve
370
- better results.
371
- * Note that changing the latent space will reset the image, points and
372
- mask (this has the same effect as `Reset Image` button).
373
- 3. Click `Edit Flexible Area` to create a mask and constrain the
374
- unmasked region to remain unchanged.
375
-
376
-
377
- """)
378
- gr.HTML("""
379
- <style>
380
- .container {
381
- position: absolute;
382
- height: 50px;
383
- text-align: center;
384
- line-height: 50px;
385
- width: 100%;
386
- }
387
- </style>
388
- <div class="container">
389
- Gradio demo supported by
390
- <img src="https://avatars.githubusercontent.com/u/10245193?s=200&v=4" height="20" width="20" style="display:inline;">
391
- <a href="https://github.com/open-mmlab/mmagic">OpenMMLab MMagic</a>
392
- </div>
393
- """)
394
- # Network & latents tab listeners
395
-
396
- def on_change_pretrained_dropdown(pretrained_value, global_state):
397
- """Function to handle model change.
398
- 1. Set pretrained value to global_state
399
- 2. Re-init images and clear all states
400
- """
401
-
402
- global_state['pretrained_weight'] = pretrained_value
403
- init_images(global_state)
404
- clear_state(global_state)
405
-
406
- return global_state, global_state["images"]['image_show']
407
-
408
- form_pretrained_dropdown.change(
409
- on_change_pretrained_dropdown,
410
- inputs=[form_pretrained_dropdown, global_state],
411
- outputs=[global_state, form_image],
412
- queue=True,
413
- )
414
-
415
- def on_click_reset_image(global_state):
416
- """Reset image to the original one and clear all states
417
- 1. Re-init images
418
- 2. Clear all states
419
- """
420
-
421
- init_images(global_state)
422
- clear_state(global_state)
423
-
424
- return global_state, global_state['images']['image_show']
425
-
426
- form_reset_image.click(
427
- on_click_reset_image,
428
- inputs=[global_state],
429
- outputs=[global_state, form_image],
430
- queue=False,
431
- )
432
-
433
- # Update parameters
434
- def on_change_update_image_seed(seed, global_state):
435
- """Function to handle generation seed change.
436
- 1. Set seed to global_state
437
- 2. Re-init images and clear all states
438
- """
439
-
440
- global_state["params"]["seed"] = int(seed)
441
- init_images(global_state)
442
- clear_state(global_state)
443
-
444
- return global_state, global_state['images']['image_show']
445
-
446
- form_seed_number.change(
447
- on_change_update_image_seed,
448
- inputs=[form_seed_number, global_state],
449
- outputs=[global_state, form_image],
450
- )
451
-
452
- def on_click_latent_space(latent_space, global_state):
453
- """Function to reset latent space to optimize.
454
- NOTE: this function we reset the image and all controls
455
- 1. Set latent-space to global_state
456
- 2. Re-init images and clear all state
457
- """
458
-
459
- global_state['params']['latent_space'] = latent_space
460
- init_images(global_state)
461
- clear_state(global_state)
462
-
463
- return global_state, global_state['images']['image_show']
464
-
465
- form_latent_space.change(on_click_latent_space,
466
- inputs=[form_latent_space, global_state],
467
- outputs=[global_state, form_image])
468
-
469
- # ==== Params
470
- form_lambda_number.change(
471
- partial(on_change_single_global_state, ["params", "motion_lambda"]),
472
- inputs=[form_lambda_number, global_state],
473
- outputs=[global_state],
474
- )
475
-
476
- def on_change_lr(lr, global_state):
477
- if lr == 0:
478
- print('lr is 0, do nothing.')
479
- return global_state
480
- else:
481
- global_state["params"]["lr"] = lr
482
- renderer = global_state['renderer']
483
- renderer.update_lr(lr)
484
- print('New optimizer: ')
485
- print(renderer.w_optim)
486
- return global_state
487
-
488
- form_lr_number.change(
489
- on_change_lr,
490
- inputs=[form_lr_number, global_state],
491
- outputs=[global_state],
492
- queue=False,
493
- )
494
-
495
- def on_click_start(global_state, image):
496
- p_in_pixels = []
497
- t_in_pixels = []
498
- valid_points = []
499
-
500
- # handle of start drag in mask editing mode
501
- global_state = preprocess_mask_info(global_state, image)
502
-
503
- # Prepare the points for the inference
504
- if len(global_state["points"]) == 0:
505
- # yield on_click_start_wo_points(global_state, image)
506
- image_raw = global_state['images']['image_raw']
507
- update_image_draw(
508
- image_raw,
509
- global_state['points'],
510
- global_state['mask'],
511
- global_state['show_mask'],
512
- global_state,
513
- )
514
-
515
- yield (
516
- global_state,
517
- 0,
518
- global_state['images']['image_show'],
519
- # gr.File.update(visible=False),
520
- gr.Button.update(interactive=True),
521
- gr.Button.update(interactive=True),
522
- gr.Button.update(interactive=True),
523
- gr.Button.update(interactive=True),
524
- gr.Button.update(interactive=True),
525
- # latent space
526
- gr.Radio.update(interactive=True),
527
- gr.Button.update(interactive=True),
528
- # NOTE: disable stop button
529
- gr.Button.update(interactive=False),
530
-
531
- # update other comps
532
- gr.Dropdown.update(interactive=True),
533
- gr.Number.update(interactive=True),
534
- gr.Number.update(interactive=True),
535
- gr.Button.update(interactive=True),
536
- gr.Button.update(interactive=True),
537
- gr.Checkbox.update(interactive=True),
538
- # gr.Number.update(interactive=True),
539
- gr.Number.update(interactive=True),
540
- )
541
- else:
542
-
543
- # Transform the points into torch tensors
544
- for key_point, point in global_state["points"].items():
545
- try:
546
- p_start = point.get("start_temp", point["start"])
547
- p_end = point["target"]
548
-
549
- if p_start is None or p_end is None:
550
- continue
551
-
552
- except KeyError:
553
- continue
554
-
555
- p_in_pixels.append(p_start)
556
- t_in_pixels.append(p_end)
557
- valid_points.append(key_point)
558
-
559
- mask = torch.tensor(global_state['mask']).float()
560
- drag_mask = 1 - mask
561
-
562
- renderer: Renderer = global_state["renderer"]
563
- global_state['temporal_params']['stop'] = False
564
- global_state['editing_state'] = 'running'
565
-
566
- # reverse points order
567
- p_to_opt = reverse_point_pairs(p_in_pixels)
568
- t_to_opt = reverse_point_pairs(t_in_pixels)
569
- print('Running with:')
570
- print(f' Source: {p_in_pixels}')
571
- print(f' Target: {t_in_pixels}')
572
- step_idx = 0
573
- last_time = time.time()
574
- while True:
575
- print_memory_usage()
576
- # add a TIMEOUT break
577
- print(f'Running time: {time.time() - last_time}')
578
- if IS_SPACE and time.time() - last_time > TIMEOUT:
579
- print('Timeout break!')
580
- break
581
- if global_state["temporal_params"]["stop"] or global_state['generator_params']["stop"]:
582
- break
583
-
584
- # do drage here!
585
- renderer._render_drag_impl(
586
- global_state['generator_params'],
587
- p_to_opt, # point
588
- t_to_opt, # target
589
- drag_mask, # mask,
590
- global_state['params']['motion_lambda'], # lambda_mask
591
- reg=0,
592
- feature_idx=5, # NOTE: do not support change for now
593
- r1=global_state['params']['r1_in_pixels'], # r1
594
- r2=global_state['params']['r2_in_pixels'], # r2
595
- # random_seed = 0,
596
- # noise_mode = 'const',
597
- trunc_psi=global_state['params']['trunc_psi'],
598
- # force_fp32 = False,
599
- # layer_name = None,
600
- # sel_channels = 3,
601
- # base_channel = 0,
602
- # img_scale_db = 0,
603
- # img_normalize = False,
604
- # untransform = False,
605
- is_drag=True,
606
- to_pil=True)
607
-
608
- if step_idx % global_state['draw_interval'] == 0:
609
- print('Current Source:')
610
- for key_point, p_i, t_i in zip(valid_points, p_to_opt,
611
- t_to_opt):
612
- global_state["points"][key_point]["start_temp"] = [
613
- p_i[1],
614
- p_i[0],
615
- ]
616
- global_state["points"][key_point]["target"] = [
617
- t_i[1],
618
- t_i[0],
619
- ]
620
- start_temp = global_state["points"][key_point][
621
- "start_temp"]
622
- print(f' {start_temp}')
623
-
624
- image_result = global_state['generator_params']['image']
625
- image_draw = update_image_draw(
626
- image_result,
627
- global_state['points'],
628
- global_state['mask'],
629
- global_state['show_mask'],
630
- global_state,
631
- )
632
- global_state['images']['image_raw'] = image_result
633
-
634
- yield (
635
- global_state,
636
- step_idx,
637
- global_state['images']['image_show'],
638
- # gr.File.update(visible=False),
639
- gr.Button.update(interactive=False),
640
- gr.Button.update(interactive=False),
641
- gr.Button.update(interactive=False),
642
- gr.Button.update(interactive=False),
643
- gr.Button.update(interactive=False),
644
- # latent space
645
- gr.Radio.update(interactive=False),
646
- gr.Button.update(interactive=False),
647
- # enable stop button in loop
648
- gr.Button.update(interactive=True),
649
-
650
- # update other comps
651
- gr.Dropdown.update(interactive=False),
652
- gr.Number.update(interactive=False),
653
- gr.Number.update(interactive=False),
654
- gr.Button.update(interactive=False),
655
- gr.Button.update(interactive=False),
656
- gr.Checkbox.update(interactive=False),
657
- # gr.Number.update(interactive=False),
658
- gr.Number.update(interactive=False),
659
- )
660
-
661
- # increate step
662
- step_idx += 1
663
-
664
- image_result = global_state['generator_params']['image']
665
- global_state['images']['image_raw'] = image_result
666
- image_draw = update_image_draw(image_result,
667
- global_state['points'],
668
- global_state['mask'],
669
- global_state['show_mask'],
670
- global_state)
671
-
672
- # fp = NamedTemporaryFile(suffix=".png", delete=False)
673
- # image_result.save(fp, "PNG")
674
-
675
- global_state['editing_state'] = 'add_points'
676
-
677
- yield (
678
- global_state,
679
- 0, # reset step to 0 after stop.
680
- global_state['images']['image_show'],
681
- # gr.File.update(visible=True, value=fp.name),
682
- gr.Button.update(interactive=True),
683
- gr.Button.update(interactive=True),
684
- gr.Button.update(interactive=True),
685
- gr.Button.update(interactive=True),
686
- gr.Button.update(interactive=True),
687
- # latent space
688
- gr.Radio.update(interactive=True),
689
- gr.Button.update(interactive=True),
690
- # NOTE: disable stop button with loop finish
691
- gr.Button.update(interactive=False),
692
-
693
- # update other comps
694
- gr.Dropdown.update(interactive=True),
695
- gr.Number.update(interactive=True),
696
- gr.Number.update(interactive=True),
697
- gr.Checkbox.update(interactive=True),
698
- gr.Number.update(interactive=True),
699
- )
700
-
701
- form_start_btn.click(
702
- on_click_start,
703
- inputs=[global_state, form_image],
704
- outputs=[
705
- global_state,
706
- form_steps_number,
707
- form_image,
708
- # form_download_result_file,
709
- # >>> buttons
710
- form_reset_image,
711
- enable_add_points,
712
- enable_add_mask,
713
- undo_points,
714
- form_reset_mask_btn,
715
- form_latent_space,
716
- form_start_btn,
717
- form_stop_btn,
718
- # <<< buttonm
719
- # >>> inputs comps
720
- form_pretrained_dropdown,
721
- form_seed_number,
722
- form_lr_number,
723
- show_mask,
724
- form_lambda_number,
725
- ],
726
- )
727
-
728
- def on_click_stop(global_state):
729
- """Function to handle stop button is clicked.
730
- 1. send a stop signal by set global_state["temporal_params"]["stop"] as True
731
- 2. Disable Stop button
732
- """
733
- global_state["temporal_params"]["stop"] = True
734
-
735
- return global_state, gr.Button.update(interactive=False)
736
-
737
- form_stop_btn.click(on_click_stop,
738
- inputs=[global_state],
739
- outputs=[global_state, form_stop_btn],
740
- queue=False)
741
-
742
- form_draw_interval_number.change(
743
- partial(
744
- on_change_single_global_state,
745
- "draw_interval",
746
- map_transform=lambda x: int(x),
747
- ),
748
- inputs=[form_draw_interval_number, global_state],
749
- outputs=[global_state],
750
- queue=False,
751
- )
752
-
753
- def on_click_remove_point(global_state):
754
- choice = global_state["curr_point"]
755
- del global_state["points"][choice]
756
-
757
- choices = list(global_state["points"].keys())
758
-
759
- if len(choices) > 0:
760
- global_state["curr_point"] = choices[0]
761
-
762
- return (
763
- gr.Dropdown.update(choices=choices, value=choices[0]),
764
- global_state,
765
- )
766
-
767
- # Mask
768
- def on_click_reset_mask(global_state):
769
- global_state['mask'] = np.ones(
770
- (
771
- global_state["images"]["image_raw"].size[1],
772
- global_state["images"]["image_raw"].size[0],
773
- ),
774
- dtype=np.uint8,
775
- )
776
- image_draw = update_image_draw(global_state['images']['image_raw'],
777
- global_state['points'],
778
- global_state['mask'],
779
- global_state['show_mask'], global_state)
780
- return global_state, image_draw
781
-
782
- form_reset_mask_btn.click(
783
- on_click_reset_mask,
784
- inputs=[global_state],
785
- outputs=[global_state, form_image],
786
- )
787
-
788
- # Image
789
- def on_click_enable_draw(global_state, image):
790
- """Function to start add mask mode.
791
- 1. Preprocess mask info from last state
792
- 2. Change editing state to add_mask
793
- 3. Set curr image with points and mask
794
- """
795
- global_state = preprocess_mask_info(global_state, image)
796
- global_state['editing_state'] = 'add_mask'
797
- image_raw = global_state['images']['image_raw']
798
- image_draw = update_image_draw(image_raw, global_state['points'],
799
- global_state['mask'], True,
800
- global_state)
801
- return (global_state,
802
- gr.Image.update(value=image_draw, interactive=True))
803
-
804
- def on_click_remove_draw(global_state, image):
805
- """Function to start remove mask mode.
806
- 1. Preprocess mask info from last state
807
- 2. Change editing state to remove_mask
808
- 3. Set curr image with points and mask
809
- """
810
- global_state = preprocess_mask_info(global_state, image)
811
- global_state['edinting_state'] = 'remove_mask'
812
- image_raw = global_state['images']['image_raw']
813
- image_draw = update_image_draw(image_raw, global_state['points'],
814
- global_state['mask'], True,
815
- global_state)
816
- return (global_state,
817
- gr.Image.update(value=image_draw, interactive=True))
818
-
819
- enable_add_mask.click(on_click_enable_draw,
820
- inputs=[global_state, form_image],
821
- outputs=[
822
- global_state,
823
- form_image,
824
- ],
825
- queue=False)
826
-
827
- def on_click_add_point(global_state, image: dict):
828
- """Function switch from add mask mode to add points mode.
829
- 1. Updaste mask buffer if need
830
- 2. Change global_state['editing_state'] to 'add_points'
831
- 3. Set current image with mask
832
- """
833
-
834
- global_state = preprocess_mask_info(global_state, image)
835
- global_state['editing_state'] = 'add_points'
836
- mask = global_state['mask']
837
- image_raw = global_state['images']['image_raw']
838
- image_draw = update_image_draw(image_raw, global_state['points'], mask,
839
- global_state['show_mask'], global_state)
840
-
841
- return (global_state,
842
- gr.Image.update(value=image_draw, interactive=False))
843
-
844
- enable_add_points.click(on_click_add_point,
845
- inputs=[global_state, form_image],
846
- outputs=[global_state, form_image],
847
- queue=False)
848
-
849
- def on_click_image(global_state, evt: gr.SelectData):
850
- """This function only support click for point selection
851
- """
852
- xy = evt.index
853
- if global_state['editing_state'] != 'add_points':
854
- print(f'In {global_state["editing_state"]} state. '
855
- 'Do not add points.')
856
-
857
- return global_state, global_state['images']['image_show']
858
-
859
- points = global_state["points"]
860
-
861
- point_idx = get_latest_points_pair(points)
862
- if point_idx is None:
863
- points[0] = {'start': xy, 'target': None}
864
- print(f'Click Image - Start - {xy}')
865
- elif points[point_idx].get('target', None) is None:
866
- points[point_idx]['target'] = xy
867
- print(f'Click Image - Target - {xy}')
868
- else:
869
- points[point_idx + 1] = {'start': xy, 'target': None}
870
- print(f'Click Image - Start - {xy}')
871
-
872
- image_raw = global_state['images']['image_raw']
873
- image_draw = update_image_draw(
874
- image_raw,
875
- global_state['points'],
876
- global_state['mask'],
877
- global_state['show_mask'],
878
- global_state,
879
- )
880
-
881
- return global_state, image_draw
882
-
883
- form_image.select(
884
- on_click_image,
885
- inputs=[global_state],
886
- outputs=[global_state, form_image],
887
- queue=False,
888
- )
889
-
890
- def on_click_clear_points(global_state):
891
- """Function to handle clear all control points
892
- 1. clear global_state['points'] (clear_state)
893
- 2. re-init network
894
- 2. re-draw image
895
- """
896
- clear_state(global_state, target='point')
897
-
898
- renderer: Renderer = global_state["renderer"]
899
- renderer.feat_refs = None
900
-
901
- image_raw = global_state['images']['image_raw']
902
- image_draw = update_image_draw(image_raw, {}, global_state['mask'],
903
- global_state['show_mask'], global_state)
904
- return global_state, image_draw
905
-
906
- undo_points.click(on_click_clear_points,
907
- inputs=[global_state],
908
- outputs=[global_state, form_image],
909
- queue=False)
910
-
911
- def on_click_show_mask(global_state, show_mask):
912
- """Function to control whether show mask on image."""
913
- global_state['show_mask'] = show_mask
914
-
915
- image_raw = global_state['images']['image_raw']
916
- image_draw = update_image_draw(
917
- image_raw,
918
- global_state['points'],
919
- global_state['mask'],
920
- global_state['show_mask'],
921
- global_state,
922
- )
923
- return global_state, image_draw
924
-
925
- show_mask.change(
926
- on_click_show_mask,
927
- inputs=[global_state, show_mask],
928
- outputs=[global_state, form_image],
929
- queue=False,
930
- )
931
-
932
- gr.close_all()
933
- app.queue(concurrency_count=1, max_size=200, api_open=False)
934
- app.launch(show_api=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/en/api/pipelines/audio_diffusion.md DELETED
@@ -1,37 +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
- # Audio Diffusion
14
-
15
- [Audio Diffusion](https://github.com/teticio/audio-diffusion) is by Robert Dargavel Smith, and it leverages the recent advances in image generation from diffusion models by converting audio samples to and from Mel spectrogram images.
16
-
17
- The original codebase, training scripts and example notebooks can be found at [teticio/audio-diffusion](https://github.com/teticio/audio-diffusion).
18
-
19
- <Tip>
20
-
21
- Make sure to check out the Schedulers [guide](/using-diffusers/schedulers) to learn how to explore the tradeoff between scheduler speed and quality, and see the [reuse components across pipelines](/using-diffusers/loading#reuse-components-across-pipelines) section to learn how to efficiently load the same components into multiple pipelines.
22
-
23
- </Tip>
24
-
25
- ## AudioDiffusionPipeline
26
- [[autodoc]] AudioDiffusionPipeline
27
- - all
28
- - __call__
29
-
30
- ## AudioPipelineOutput
31
- [[autodoc]] pipelines.AudioPipelineOutput
32
-
33
- ## ImagePipelineOutput
34
- [[autodoc]] pipelines.ImagePipelineOutput
35
-
36
- ## Mel
37
- [[autodoc]] Mel
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/en/api/pipelines/overview.md DELETED
@@ -1,36 +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
- # Pipelines
14
-
15
- Pipelines provide a simple way to run state-of-the-art diffusion models in inference by bundling all of the necessary components (multiple independently-trained models, schedulers, and processors) into a single end-to-end class. Pipelines are flexible and they can be adapted to use different scheduler or even model components.
16
-
17
- All pipelines are built from the base [`DiffusionPipeline`] class which provides basic functionality for loading, downloading, and saving all the components.
18
-
19
- <Tip warning={true}>
20
-
21
- Pipelines do not offer any training functionality. You'll notice PyTorch's autograd is disabled by decorating the [`~DiffusionPipeline.__call__`] method with a [`torch.no_grad`](https://pytorch.org/docs/stable/generated/torch.no_grad.html) decorator because pipelines should not be used for training. If you're interested in training, please take a look at the [Training](../traininig/overview) guides instead!
22
-
23
- </Tip>
24
-
25
- ## DiffusionPipeline
26
-
27
- [[autodoc]] DiffusionPipeline
28
- - all
29
- - __call__
30
- - device
31
- - to
32
- - components
33
-
34
- ## FlaxDiffusionPipeline
35
-
36
- [[autodoc]] pipelines.pipeline_flax_utils.FlaxDiffusionPipeline
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/en/api/pipelines/stable_diffusion/overview.md DELETED
@@ -1,180 +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
- # Stable Diffusion pipelines
14
-
15
- Stable Diffusion is a text-to-image latent diffusion model created by the researchers and engineers from [CompVis](https://github.com/CompVis), [Stability AI](https://stability.ai/) and [LAION](https://laion.ai/). Latent diffusion applies the diffusion process over a lower dimensional latent space to reduce memory and compute complexity. This specific type of diffusion model was proposed in [High-Resolution Image Synthesis with Latent Diffusion Models](https://huggingface.co/papers/2112.10752) by Robin Rombach, Andreas Blattmann, Dominik Lorenz, Patrick Esser, Björn Ommer.
16
-
17
- Stable Diffusion is trained on 512x512 images from a subset of the LAION-5B dataset. This model uses a frozen CLIP ViT-L/14 text encoder to condition the model on text prompts. With its 860M UNet and 123M text encoder, the model is relatively lightweight and can run on consumer GPUs.
18
-
19
- For more details about how Stable Diffusion works and how it differs from the base latent diffusion model, take a look at the Stability AI [announcement](https://stability.ai/blog/stable-diffusion-announcement) and our own [blog post](https://huggingface.co/blog/stable_diffusion#how-does-stable-diffusion-work) for more technical details.
20
-
21
- You can find the original codebase for Stable Diffusion v1.0 at [CompVis/stable-diffusion](https://github.com/CompVis/stable-diffusion) and Stable Diffusion v2.0 at [Stability-AI/stablediffusion](https://github.com/Stability-AI/stablediffusion) as well as their original scripts for various tasks. Additional official checkpoints for the different Stable Diffusion versions and tasks can be found on the [CompVis](https://huggingface.co/CompVis), [Runway](https://huggingface.co/runwayml), and [Stability AI](https://huggingface.co/stabilityai) Hub organizations. Explore these organizations to find the best checkpoint for your use-case!
22
-
23
- The table below summarizes the available Stable Diffusion pipelines, their supported tasks, and an interactive demo:
24
-
25
- <div class="flex justify-center">
26
- <div class="rounded-xl border border-gray-200">
27
- <table class="min-w-full divide-y-2 divide-gray-200 bg-white text-sm">
28
- <thead>
29
- <tr>
30
- <th class="px-4 py-2 font-medium text-gray-900 text-left">
31
- Pipeline
32
- </th>
33
- <th class="px-4 py-2 font-medium text-gray-900 text-left">
34
- Supported tasks
35
- </th>
36
- <th class="px-4 py-2 font-medium text-gray-900 text-left">
37
- Space
38
- </th>
39
-
40
- </tr>
41
- </thead>
42
-
43
- <tbody class="divide-y divide-gray-200">
44
- <tr>
45
- <td class="px-4 py-2 text-gray-700">
46
- <a href="./text2img">StableDiffusion</a>
47
- </td>
48
- <td class="px-4 py-2 text-gray-700">text-to-image</td>
49
- <td class="px-4 py-2"><a href="https://huggingface.co/spaces/stabilityai/stable-diffusion"><img src="https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue"/></a>
50
- </td>
51
- </tr>
52
-
53
- <tr>
54
- <td class="px-4 py-2 text-gray-700">
55
- <a href="./img2img">StableDiffusionImg2Img</a>
56
- </td>
57
- <td class="px-4 py-2 text-gray-700">image-to-image</td>
58
- <td class="px-4 py-2"><a href="https://huggingface.co/spaces/huggingface/diffuse-the-rest"><img src="https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue"/></a>
59
- </td>
60
- </tr>
61
-
62
- <tr>
63
- <td class="px-4 py-2 text-gray-700">
64
- <a href="./inpaint">StableDiffusionInpaint</a>
65
- </td>
66
- <td class="px-4 py-2 text-gray-700">inpainting</td>
67
- <td class="px-4 py-2"><a href="https://huggingface.co/spaces/runwayml/stable-diffusion-inpainting"><img src="https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue"/></a>
68
- </td>
69
- </tr>
70
-
71
- <tr>
72
- <td class="px-4 py-2 text-gray-700">
73
- <a href="./depth2img">StableDiffusionDepth2Img</a>
74
- </td>
75
- <td class="px-4 py-2 text-gray-700">depth-to-image</td>
76
- <td class="px-4 py-2"><a href="https://huggingface.co/spaces/radames/stable-diffusion-depth2img"><img src="https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue"/></a>
77
- </td>
78
- </tr>
79
-
80
- <tr>
81
- <td class="px-4 py-2 text-gray-700">
82
- <a href="./image_variation">StableDiffusionImageVariation</a>
83
- </td>
84
- <td class="px-4 py-2 text-gray-700">image variation</td>
85
- <td class="px-4 py-2"><a href="https://huggingface.co/spaces/lambdalabs/stable-diffusion-image-variations"><img src="https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue"/></a>
86
- </td>
87
- </tr>
88
-
89
- <tr>
90
- <td class="px-4 py-2 text-gray-700">
91
- <a href="./stable_diffusion_safe">StableDiffusionPipelineSafe</a>
92
- </td>
93
- <td class="px-4 py-2 text-gray-700">filtered text-to-image</td>
94
- <td class="px-4 py-2"><a href="https://huggingface.co/spaces/AIML-TUDA/unsafe-vs-safe-stable-diffusion"><img src="https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue"/></a>
95
- </td>
96
- </tr>
97
-
98
- <tr>
99
- <td class="px-4 py-2 text-gray-700">
100
- <a href="./stable_diffusion_2">StableDiffusion2</a>
101
- </td>
102
- <td class="px-4 py-2 text-gray-700">text-to-image, inpainting, depth-to-image, super-resolution</td>
103
- <td class="px-4 py-2"><a href="https://huggingface.co/spaces/stabilityai/stable-diffusion"><img src="https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue"/></a>
104
- </td>
105
- </tr>
106
-
107
- <tr>
108
- <td class="px-4 py-2 text-gray-700">
109
- <a href="./stable_diffusion_xl">StableDiffusionXL</a>
110
- </td>
111
- <td class="px-4 py-2 text-gray-700">text-to-image, image-to-image</td>
112
- <td class="px-4 py-2"><a href="https://huggingface.co/spaces/RamAnanth1/stable-diffusion-xl"><img src="https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue"/></a>
113
- </td>
114
- </tr>
115
-
116
- <tr>
117
- <td class="px-4 py-2 text-gray-700">
118
- <a href="./latent_upscale">StableDiffusionLatentUpscale</a>
119
- </td>
120
- <td class="px-4 py-2 text-gray-700">super-resolution</td>
121
- <td class="px-4 py-2"><a href="https://huggingface.co/spaces/huggingface-projects/stable-diffusion-latent-upscaler"><img src="https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue"/></a>
122
- </td>
123
- </tr>
124
-
125
- <tr>
126
- <td class="px-4 py-2 text-gray-700">
127
- <a href="./upscale">StableDiffusionUpscale</a>
128
- </td>
129
- <td class="px-4 py-2 text-gray-700">super-resolution</td>
130
- </tr>
131
-
132
- <tr>
133
- <td class="px-4 py-2 text-gray-700">
134
- <a href="./ldm3d_diffusion">StableDiffusionLDM3D</a>
135
- </td>
136
- <td class="px-4 py-2 text-gray-700">text-to-rgb, text-to-depth</td>
137
- <td class="px-4 py-2"><a href="https://huggingface.co/spaces/r23/ldm3d-space"><img src="https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue"/></a>
138
- </td>
139
- </tr>
140
- </tbody>
141
- </table>
142
- </div>
143
- </div>
144
-
145
- ## Tips
146
-
147
- To help you get the most out of the Stable Diffusion pipelines, here are a few tips for improving performance and usability. These tips are applicable to all Stable Diffusion pipelines.
148
-
149
- ### Explore tradeoff between speed and quality
150
-
151
- [`StableDiffusionPipeline`] uses the [`PNDMScheduler`] by default, but 🤗 Diffusers provides many other schedulers (some of which are faster or output better quality) that are compatible. For example, if you want to use the [`EulerDiscreteScheduler`] instead of the default:
152
-
153
- ```py
154
- from diffusers import StableDiffusionPipeline, EulerDiscreteScheduler
155
-
156
- pipeline = StableDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4")
157
- pipeline.scheduler = EulerDiscreteScheduler.from_config(pipeline.scheduler.config)
158
-
159
- # or
160
- euler_scheduler = EulerDiscreteScheduler.from_pretrained("CompVis/stable-diffusion-v1-4", subfolder="scheduler")
161
- pipeline = StableDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", scheduler=euler_scheduler)
162
- ```
163
-
164
- ### Reuse pipeline components to save memory
165
-
166
- To save memory and use the same components across multiple pipelines, use the `.components` method to avoid loading weights into RAM more than once.
167
-
168
- ```py
169
- from diffusers import (
170
- StableDiffusionPipeline,
171
- StableDiffusionImg2ImgPipeline,
172
- StableDiffusionInpaintPipeline,
173
- )
174
-
175
- text2img = StableDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4")
176
- img2img = StableDiffusionImg2ImgPipeline(**text2img.components)
177
- inpaint = StableDiffusionInpaintPipeline(**text2img.components)
178
-
179
- # now you can use text2img(...), img2img(...), inpaint(...) just like the call methods of each respective pipeline
180
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Anonymous-sub/Rerender/ControlNet/annotator/uniformer/mmcv/parallel/collate.py DELETED
@@ -1,84 +0,0 @@
1
- # Copyright (c) OpenMMLab. All rights reserved.
2
- from collections.abc import Mapping, Sequence
3
-
4
- import torch
5
- import torch.nn.functional as F
6
- from torch.utils.data.dataloader import default_collate
7
-
8
- from .data_container import DataContainer
9
-
10
-
11
- def collate(batch, samples_per_gpu=1):
12
- """Puts each data field into a tensor/DataContainer with outer dimension
13
- batch size.
14
-
15
- Extend default_collate to add support for
16
- :type:`~mmcv.parallel.DataContainer`. There are 3 cases.
17
-
18
- 1. cpu_only = True, e.g., meta data
19
- 2. cpu_only = False, stack = True, e.g., images tensors
20
- 3. cpu_only = False, stack = False, e.g., gt bboxes
21
- """
22
-
23
- if not isinstance(batch, Sequence):
24
- raise TypeError(f'{batch.dtype} is not supported.')
25
-
26
- if isinstance(batch[0], DataContainer):
27
- stacked = []
28
- if batch[0].cpu_only:
29
- for i in range(0, len(batch), samples_per_gpu):
30
- stacked.append(
31
- [sample.data for sample in batch[i:i + samples_per_gpu]])
32
- return DataContainer(
33
- stacked, batch[0].stack, batch[0].padding_value, cpu_only=True)
34
- elif batch[0].stack:
35
- for i in range(0, len(batch), samples_per_gpu):
36
- assert isinstance(batch[i].data, torch.Tensor)
37
-
38
- if batch[i].pad_dims is not None:
39
- ndim = batch[i].dim()
40
- assert ndim > batch[i].pad_dims
41
- max_shape = [0 for _ in range(batch[i].pad_dims)]
42
- for dim in range(1, batch[i].pad_dims + 1):
43
- max_shape[dim - 1] = batch[i].size(-dim)
44
- for sample in batch[i:i + samples_per_gpu]:
45
- for dim in range(0, ndim - batch[i].pad_dims):
46
- assert batch[i].size(dim) == sample.size(dim)
47
- for dim in range(1, batch[i].pad_dims + 1):
48
- max_shape[dim - 1] = max(max_shape[dim - 1],
49
- sample.size(-dim))
50
- padded_samples = []
51
- for sample in batch[i:i + samples_per_gpu]:
52
- pad = [0 for _ in range(batch[i].pad_dims * 2)]
53
- for dim in range(1, batch[i].pad_dims + 1):
54
- pad[2 * dim -
55
- 1] = max_shape[dim - 1] - sample.size(-dim)
56
- padded_samples.append(
57
- F.pad(
58
- sample.data, pad, value=sample.padding_value))
59
- stacked.append(default_collate(padded_samples))
60
- elif batch[i].pad_dims is None:
61
- stacked.append(
62
- default_collate([
63
- sample.data
64
- for sample in batch[i:i + samples_per_gpu]
65
- ]))
66
- else:
67
- raise ValueError(
68
- 'pad_dims should be either None or integers (1-3)')
69
-
70
- else:
71
- for i in range(0, len(batch), samples_per_gpu):
72
- stacked.append(
73
- [sample.data for sample in batch[i:i + samples_per_gpu]])
74
- return DataContainer(stacked, batch[0].stack, batch[0].padding_value)
75
- elif isinstance(batch[0], Sequence):
76
- transposed = zip(*batch)
77
- return [collate(samples, samples_per_gpu) for samples in transposed]
78
- elif isinstance(batch[0], Mapping):
79
- return {
80
- key: collate([d[key] for d in batch], samples_per_gpu)
81
- for key in batch[0]
82
- }
83
- else:
84
- return default_collate(batch)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AriaMei/TTSdemo/utils.py DELETED
@@ -1,267 +0,0 @@
1
- import os
2
- import glob
3
- import sys
4
- import argparse
5
- import logging
6
- import json
7
- import subprocess
8
- import numpy as np
9
- from scipy.io.wavfile import read
10
- import torch
11
-
12
- MATPLOTLIB_FLAG = False
13
-
14
- logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
15
- logger = logging
16
-
17
-
18
- def load_checkpoint(checkpoint_path, model, optimizer=None):
19
- assert os.path.isfile(checkpoint_path)
20
- checkpoint_dict = torch.load(checkpoint_path, map_location='cpu')
21
- iteration = checkpoint_dict['iteration']
22
- learning_rate = checkpoint_dict['learning_rate']
23
- if optimizer is not None:
24
- optimizer.load_state_dict(checkpoint_dict['optimizer'])
25
- saved_state_dict = checkpoint_dict['model']
26
- if hasattr(model, 'module'):
27
- state_dict = model.module.state_dict()
28
- else:
29
- state_dict = model.state_dict()
30
- new_state_dict= {}
31
- for k, v in state_dict.items():
32
- try:
33
- new_state_dict[k] = saved_state_dict[k]
34
- except:
35
- print("%s is not in the checkpoint" % k) or logger.info("%s is not in the checkpoint" % k)
36
- new_state_dict[k] = v
37
- if hasattr(model, 'module'):
38
- model.module.load_state_dict(new_state_dict)
39
- else:
40
- model.load_state_dict(new_state_dict)
41
- logger.info("Loaded checkpoint '{}' (iteration {})" .format(
42
- checkpoint_path, iteration))
43
- print("Loaded checkpoint '{}' (iteration {}) " .format(
44
- checkpoint_path, iteration))
45
- return model, optimizer, learning_rate, iteration
46
-
47
-
48
- def save_checkpoint(model, optimizer, learning_rate, iteration, checkpoint_path):
49
- ckptname = checkpoint_path.split("/")[-1]
50
- newest_step = int(ckptname.split(".")[0].split("_")[1])
51
- last_ckptname = checkpoint_path.replace(str(newest_step), str(newest_step-1200))
52
- if newest_step >= 1200:
53
- os.system(f"rm {last_ckptname}")
54
- logger.info("Saving model and optimizer state at iteration {} to {}".format(
55
- iteration, checkpoint_path))
56
- print("Saving model and optimizer state at iteration {} to {}".format(
57
- iteration, checkpoint_path))
58
- if hasattr(model, 'module'):
59
- state_dict = model.module.state_dict()
60
- else:
61
- state_dict = model.state_dict()
62
- torch.save({'model': state_dict,
63
- 'iteration': iteration,
64
- 'optimizer': optimizer.state_dict(),
65
- 'learning_rate': learning_rate}, checkpoint_path)
66
-
67
-
68
- def summarize(writer, global_step, scalars={}, histograms={}, images={}, audios={}, audio_sampling_rate=22050):
69
- for k, v in scalars.items():
70
- writer.add_scalar(k, v, global_step)
71
- for k, v in histograms.items():
72
- writer.add_histogram(k, v, global_step)
73
- for k, v in images.items():
74
- writer.add_image(k, v, global_step, dataformats='HWC')
75
- for k, v in audios.items():
76
- writer.add_audio(k, v, global_step, audio_sampling_rate)
77
-
78
-
79
- def latest_checkpoint_path(dir_path, regex="G_*.pth"):
80
- f_list = glob.glob(os.path.join(dir_path, regex))
81
- f_list.sort(key=lambda f: int("".join(filter(str.isdigit, f))))
82
- x = f_list[-1]
83
- print(x)
84
- return x
85
-
86
-
87
- def plot_spectrogram_to_numpy(spectrogram):
88
- global MATPLOTLIB_FLAG
89
- if not MATPLOTLIB_FLAG:
90
- import matplotlib
91
- matplotlib.use("Agg")
92
- MATPLOTLIB_FLAG = True
93
- mpl_logger = logging.getLogger('matplotlib')
94
- mpl_logger.setLevel(logging.WARNING)
95
- import matplotlib.pylab as plt
96
- import numpy as np
97
-
98
- fig, ax = plt.subplots(figsize=(10,2))
99
- im = ax.imshow(spectrogram, aspect="auto", origin="lower",
100
- interpolation='none')
101
- plt.colorbar(im, ax=ax)
102
- plt.xlabel("Frames")
103
- plt.ylabel("Channels")
104
- plt.tight_layout()
105
-
106
- fig.canvas.draw()
107
- data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
108
- data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
109
- plt.close()
110
- return data
111
-
112
-
113
- def plot_alignment_to_numpy(alignment, info=None):
114
- global MATPLOTLIB_FLAG
115
- if not MATPLOTLIB_FLAG:
116
- import matplotlib
117
- matplotlib.use("Agg")
118
- MATPLOTLIB_FLAG = True
119
- mpl_logger = logging.getLogger('matplotlib')
120
- mpl_logger.setLevel(logging.WARNING)
121
- import matplotlib.pylab as plt
122
- import numpy as np
123
-
124
- fig, ax = plt.subplots(figsize=(6, 4))
125
- im = ax.imshow(alignment.transpose(), aspect='auto', origin='lower',
126
- interpolation='none')
127
- fig.colorbar(im, ax=ax)
128
- xlabel = 'Decoder timestep'
129
- if info is not None:
130
- xlabel += '\n\n' + info
131
- plt.xlabel(xlabel)
132
- plt.ylabel('Encoder timestep')
133
- plt.tight_layout()
134
-
135
- fig.canvas.draw()
136
- data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
137
- data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
138
- plt.close()
139
- return data
140
-
141
-
142
- def load_wav_to_torch(full_path):
143
- sampling_rate, data = read(full_path)
144
- return torch.FloatTensor(data.astype(np.float32)), sampling_rate
145
-
146
-
147
- def load_filepaths_and_text(filename, split="|"):
148
- with open(filename, encoding='utf-8') as f:
149
- filepaths_and_text = [line.strip().split(split) for line in f]
150
- return filepaths_and_text
151
-
152
-
153
- def get_hparams(init=True):
154
- parser = argparse.ArgumentParser()
155
- parser.add_argument('-c', '--config', type=str, default="./configs/base.json",
156
- help='JSON file for configuration')
157
- parser.add_argument('-m', '--model', type=str, required=True,
158
- help='Model name')
159
-
160
- args = parser.parse_args()
161
- model_dir = os.path.join("./logs", args.model)
162
-
163
- if not os.path.exists(model_dir):
164
- os.makedirs(model_dir)
165
-
166
- config_path = args.config
167
- config_save_path = os.path.join(model_dir, "config.json")
168
- if init:
169
- with open(config_path, "r") as f:
170
- data = f.read()
171
- with open(config_save_path, "w") as f:
172
- f.write(data)
173
- else:
174
- with open(config_save_path, "r") as f:
175
- data = f.read()
176
- config = json.loads(data)
177
-
178
- hparams = HParams(**config)
179
- hparams.model_dir = model_dir
180
- return hparams
181
-
182
-
183
- def get_hparams_from_dir(model_dir):
184
- config_save_path = os.path.join(model_dir, "config.json")
185
- with open(config_save_path, "r") as f:
186
- data = f.read()
187
- config = json.loads(data)
188
-
189
- hparams =HParams(**config)
190
- hparams.model_dir = model_dir
191
- return hparams
192
-
193
-
194
- def get_hparams_from_file(config_path):
195
- with open(config_path, "r") as f:
196
- data = f.read()
197
- config = json.loads(data)
198
-
199
- hparams =HParams(**config)
200
- return hparams
201
-
202
-
203
- def check_git_hash(model_dir):
204
- source_dir = os.path.dirname(os.path.realpath(__file__))
205
- if not os.path.exists(os.path.join(source_dir, ".git")):
206
- logger.warn("{} is not a git repository, therefore hash value comparison will be ignored.".format(
207
- source_dir
208
- ))
209
- return
210
-
211
- cur_hash = subprocess.getoutput("git rev-parse HEAD")
212
-
213
- path = os.path.join(model_dir, "githash")
214
- if os.path.exists(path):
215
- saved_hash = open(path).read()
216
- if saved_hash != cur_hash:
217
- logger.warn("git hash values are different. {}(saved) != {}(current)".format(
218
- saved_hash[:8], cur_hash[:8]))
219
- else:
220
- open(path, "w").write(cur_hash)
221
-
222
-
223
- def get_logger(model_dir, filename="train.log"):
224
- global logger
225
- logger = logging.getLogger(os.path.basename(model_dir))
226
- logger.setLevel(logging.DEBUG)
227
-
228
- formatter = logging.Formatter("%(asctime)s\t%(name)s\t%(levelname)s\t%(message)s")
229
- if not os.path.exists(model_dir):
230
- os.makedirs(model_dir)
231
- h = logging.FileHandler(os.path.join(model_dir, filename))
232
- h.setLevel(logging.DEBUG)
233
- h.setFormatter(formatter)
234
- logger.addHandler(h)
235
- return logger
236
-
237
-
238
- class HParams():
239
- def __init__(self, **kwargs):
240
- for k, v in kwargs.items():
241
- if type(v) == dict:
242
- v = HParams(**v)
243
- self[k] = v
244
-
245
- def keys(self):
246
- return self.__dict__.keys()
247
-
248
- def items(self):
249
- return self.__dict__.items()
250
-
251
- def values(self):
252
- return self.__dict__.values()
253
-
254
- def __len__(self):
255
- return len(self.__dict__)
256
-
257
- def __getitem__(self, key):
258
- return getattr(self, key)
259
-
260
- def __setitem__(self, key, value):
261
- return setattr(self, key, value)
262
-
263
- def __contains__(self, key):
264
- return key in self.__dict__
265
-
266
- def __repr__(self):
267
- return self.__dict__.__repr__()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_internal/metadata/importlib/_compat.py DELETED
@@ -1,55 +0,0 @@
1
- import importlib.metadata
2
- from typing import Any, Optional, Protocol, cast
3
-
4
-
5
- class BadMetadata(ValueError):
6
- def __init__(self, dist: importlib.metadata.Distribution, *, reason: str) -> None:
7
- self.dist = dist
8
- self.reason = reason
9
-
10
- def __str__(self) -> str:
11
- return f"Bad metadata in {self.dist} ({self.reason})"
12
-
13
-
14
- class BasePath(Protocol):
15
- """A protocol that various path objects conform.
16
-
17
- This exists because importlib.metadata uses both ``pathlib.Path`` and
18
- ``zipfile.Path``, and we need a common base for type hints (Union does not
19
- work well since ``zipfile.Path`` is too new for our linter setup).
20
-
21
- This does not mean to be exhaustive, but only contains things that present
22
- in both classes *that we need*.
23
- """
24
-
25
- @property
26
- def name(self) -> str:
27
- raise NotImplementedError()
28
-
29
- @property
30
- def parent(self) -> "BasePath":
31
- raise NotImplementedError()
32
-
33
-
34
- def get_info_location(d: importlib.metadata.Distribution) -> Optional[BasePath]:
35
- """Find the path to the distribution's metadata directory.
36
-
37
- HACK: This relies on importlib.metadata's private ``_path`` attribute. Not
38
- all distributions exist on disk, so importlib.metadata is correct to not
39
- expose the attribute as public. But pip's code base is old and not as clean,
40
- so we do this to avoid having to rewrite too many things. Hopefully we can
41
- eliminate this some day.
42
- """
43
- return getattr(d, "_path", None)
44
-
45
-
46
- def get_dist_name(dist: importlib.metadata.Distribution) -> str:
47
- """Get the distribution's project name.
48
-
49
- The ``name`` attribute is only available in Python 3.10 or later. We are
50
- targeting exactly that, but Mypy does not know this.
51
- """
52
- name = cast(Any, dist).name
53
- if not isinstance(name, str):
54
- raise BadMetadata(dist, reason="invalid metadata entry 'name'")
55
- return name
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/_vendor/tomli/_types.py DELETED
@@ -1,10 +0,0 @@
1
- # SPDX-License-Identifier: MIT
2
- # SPDX-FileCopyrightText: 2021 Taneli Hukkinen
3
- # Licensed to PSF under a Contributor Agreement.
4
-
5
- from typing import Any, Callable, Tuple
6
-
7
- # Type annotations
8
- ParseFloat = Callable[[str], Any]
9
- Key = Tuple[str, ...]
10
- Pos = int
 
 
 
 
 
 
 
 
 
 
 
spaces/BIOML-SVM/SVM/msa.py DELETED
@@ -1,62 +0,0 @@
1
- import glob
2
- import itertools
3
- from pathlib import Path
4
- from typing import List, Tuple, Optional, Dict, NamedTuple, Union, Callable
5
- import string
6
-
7
- import numpy as np
8
- import torch
9
- from scipy.spatial.distance import squareform, pdist, cdist
10
- from Bio import SeqIO
11
- #import biotite.structure as bs
12
- #from biotite.structure.io.pdbx import PDBxFile, get_structure
13
- #from biotite.database import rcsb
14
- from tqdm import tqdm
15
- import pandas as pd
16
-
17
-
18
- # This is an efficient way to delete lowercase characters and insertion characters from a string
19
- deletekeys = dict.fromkeys(string.ascii_lowercase)
20
- deletekeys["."] = None
21
- deletekeys["*"] = None
22
- translation = str.maketrans(deletekeys)
23
-
24
-
25
- def read_sequence(filename: str) -> Tuple[str, str]:
26
- """ Reads the first (reference) sequences from a fasta or MSA file."""
27
- record = next(SeqIO.parse(filename, "fasta"))
28
- return record.description, str(record.seq)
29
-
30
- def remove_insertions(sequence: str) -> str:
31
- """ Removes any insertions into the sequence. Needed to load aligned sequences in an MSA. """
32
- return sequence.translate(translation)
33
-
34
- def read_msa(filename: str) -> List[Tuple[str, str]]:
35
- """ Reads the sequences from an MSA file, automatically removes insertions."""
36
- return [(record.description, remove_insertions(str(record.seq))) for record in SeqIO.parse(filename, "fasta")]
37
-
38
-
39
- def greedy_select(msa: List[Tuple[str, str]], num_seqs: int, mode: str = "max") -> List[Tuple[str, str]]:
40
- """
41
- Select sequences from the MSA to maximize the hamming distance
42
- Alternatively, can use hhfilter
43
- """
44
- assert mode in ("max", "min")
45
- if len(msa) <= num_seqs:
46
- return msa
47
-
48
- array = np.array([list(seq) for _, seq in msa], dtype=np.bytes_).view(np.uint8)
49
-
50
- optfunc = np.argmax if mode == "max" else np.argmin
51
- all_indices = np.arange(len(msa))
52
- indices = [0]
53
- pairwise_distances = np.zeros((0, len(msa)))
54
- for _ in range(num_seqs - 1):
55
- dist = cdist(array[indices[-1:]], array, "hamming")
56
- pairwise_distances = np.concatenate([pairwise_distances, dist])
57
- shifted_distance = np.delete(pairwise_distances, indices, axis=1).mean(0)
58
- shifted_index = optfunc(shifted_distance)
59
- index = np.delete(all_indices, indices)[shifted_index]
60
- indices.append(index)
61
- indices = sorted(indices)
62
- return [msa[idx] for idx in indices]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Benson/text-generation/Examples/Ataque Areo Comando Mod Apk.md DELETED
@@ -1,92 +0,0 @@
1
- <br />
2
- <h1>Air Offense Command Mod APK: Un emocionante juego de árcade para Android</h1>
3
- <p>Si usted está buscando un juego de árcade divertido y desafiante que pondrá a prueba sus habilidades y reflejos, es posible que desee probar Air Offense Command Mod APK. Esta es una versión modificada del juego original de Air Offense Command, que está disponible en Google Play Store. En este juego, usted dirigirá una fuerza de bombardero ragtag para salvar a su país de la aniquilación mediante el lanzamiento de un ataque preventivo desesperado contra el enemigo. Tendrás que mejorar tus aviones con mejores bombas, cohetes, armaduras y motores, y esquivar el fuego enemigo, misiles y cazas. ¿Estás listo para asumir esta misión? Aquí está todo lo que necesita saber sobre Air Offense Command Mod APK.</p>
4
- <h2>ataque aéreo comando mod apk</h2><br /><p><b><b>DOWNLOAD</b> &#8250;&#8250;&#8250; <a href="https://bltlly.com/2v6IP7">https://bltlly.com/2v6IP7</a></b></p><br /><br />
5
- <h2>¿Qué es el Comando de Ataque Aéreo? </h2>
6
- <p>Air Offense Command es un juego árcade desarrollado por Ensit Media, un estudio de juegos indie de Corea del Sur. El juego fue lanzado en abril de 2022 y ha recibido más de 50.000 descargas y críticas positivas de los jugadores. El juego cuenta con gráficos de estilo retro, controles simples y un juego adictivo. El juego está inspirado en juegos de árcade clásicos como 1942, Raiden y Sky Force.</p>
7
- <h3>¿Cómo se juega Air Offense Command? </h3>
8
- <p>El juego de Air Offense Command es simple pero desafiante. Controlarás un avión bombardero que vuela automáticamente de izquierda a derecha. Puede tocar la pantalla para lanzar bombas o deslizar para lanzar cohetes. También puede inclinar el dispositivo para mover el avión hacia arriba y hacia abajo. Su objetivo es destruir tantos objetivos enemigos como sea posible evitando sus ataques. Te enfrentarás a diferentes tipos de enemigos, como tanques, camiones, barcos, cañones, misiles y combatientes. También encontrarás batallas contra jefes que requerirán más estrategia y habilidad. </p>
9
- <h3>¿Cómo actualizar su avión en Air Offense Command? </h3>
10
-
11
- <h2>¿Qué es el comando de ataque aéreo Mod APK? </h2>
12
- <p>Air Offense Command Mod APK es una versión modificada del juego original que ofrece algunas ventajas y características que no están disponibles en la versión oficial. Algunos de los beneficios de usar Air Offense Command Mod APK son:</p>
13
- <h3>Monedas ilimitadas</h3>
14
- <p>Con Air Offense Command Mod APK, usted tendrá monedas ilimitadas que puede utilizar para actualizar su avión sin limitaciones. Puedes maximizar todas las mejoras y desbloquear todos los aviones sin gastar dinero real. </p>
15
- <h3>No hay anuncios</h3>
16
- <p>Con Air Offense Command Mod APK, no verá ningún anuncio que pueda interrumpir su juego o molestarlo. Puedes disfrutar del juego sin distracciones ni interrupciones. </p>
17
- <h3>Fácil instalación</h3>
18
- <p>Con Air Offense Command Mod APK, no es necesario rootear su dispositivo o instalar aplicaciones o archivos adicionales. Solo necesitas descargar el archivo APK de una fuente confiable e instalarlo en tu dispositivo como cualquier otra aplicación. </p>
19
- <h2>¿Cómo descargar e instalar Air Offense Command Mod APK? </h2>
20
- <p>Si desea descargar e instalar Air Offense Command Mod APK en su dispositivo Android, puede seguir estos sencillos pasos:</p>
21
- <p></p>
22
- <ol>
23
- <li>Ir a un sitio web de confianza que ofrece Air Ofensiva Comando Mod APK para su descarga. Por ejemplo, puede utilizar [APKCombo]( 1 ), que es un descargador APK seguro y rápido. </li>
24
- <li> Búsqueda de Air Offense Command Mod APK en el sitio web y haga clic en el botón de descarga. </li>
25
- <li>Espere a que la descarga termine y localice el archivo APK en su dispositivo. </li>
26
- <li>Antes de instalar el archivo APK, asegúrese de que ha habilitado la opción de instalar aplicaciones de fuentes desconocidas en la configuración del dispositivo. </li>
27
- <li>Toque en el archivo APK y siga las instrucciones para instalarlo en su dispositivo. </li>
28
- <li> Iniciar el juego y disfrutar de jugar Air Offense Command Mod APK.</li>
29
- </ol>
30
- <h2>Una tabla de comparación de Air Offense Command vs Air Offense Command Mod APK</h2>
31
-
32
- <tabla>
33
- <tr>
34
- <th>Característica</th>
35
- <th>Comando de Ataque Aéreo</th>
36
- <th>Comando de ataque aéreo Mod APK</th>
37
- </tr>
38
- <tr>
39
- <td>Monedas</td>
40
- <td>Limitado, ganado por jugar el juego o comprar con dinero real</td>
41
- <td>Ilimitado, disponible gratis</td>
42
- </tr>
43
- <tr>
44
- <td>Anuncios</td>
45
- <td>Sí, se muestra durante el juego o antes de iniciar un nivel</td>
46
- <td>No, eliminado por completo</td>
47
- </tr>
48
- <tr>
49
- <td>Instalación</td>
50
- <td>Fácil, disponible en Google Play Store</td>
51
- <td>Fácil, disponible en APKCombo u otros sitios web</td>
52
- </tr>
53
- <tr>
54
- <td>Actualizaciones</td>
55
- <td>Sí, automático o manual a través de Google Play Store</td>
56
- <td>No, manual a través de la descarga e instalación de un nuevo archivo APK</td>
57
- </tr>
58
- <tr>
59
- <td>Seguridad</td>
60
- <td>Sí, verificado por Google Play Protect</td>
61
- <td>No, no verificado por Google Play Protect, puede contener malware o virus</td>
62
- </tr>
63
- <tr>
64
- <td>Soporte</td>
65
- <td>Sí, proporcionado por el desarrollador a través de correo electrónico o redes sociales</td>
66
- <td>No, no proporcionado por el desarrollador, puede encontrar errores o problemas técnicos</td>
67
- </tr>
68
- <tr>
69
- <td>Compatibilidad</td>
70
- <td>Sí, compatible con la mayoría de dispositivos Android con Android 4.4 o superior</td>
71
- <td>No, no es compatible con algunos dispositivos o versiones de Android, puede bloquearse o no funciona correctamente</td>
72
- </tr>
73
- <h2>Conclusión</h2>
74
-
75
- <h2>Preguntas frecuentes (preguntas frecuentes)</h2>
76
- <h3>Q: ¿Es libre el comando de ataque aéreo Mod APK? </h3>
77
- <p>A: Sí, Air Offense Command Mod APK es gratis para descargar y jugar. No es necesario pagar dinero para usarlo. </p>
78
- <h3>Q: ¿Es legal el Comando de Ataque Aéreo Mod APK? </h3>
79
- <p>A: No, Comando de Ataque Aéreo Mod APK no es legal. Es una versión modificada del juego original que viola los términos y condiciones del desarrollador y Google Play Store. Usted puede enfrentar consecuencias legales si lo usa. </p>
80
- <h3>Q: ¿Es seguro el Comando de Ataque Aéreo Mod APK? </h3>
81
- <p>A: No, Comando de ataque aéreo Mod APK no es seguro. No está verificado por Google Play Protect y puede contener malware o virus que pueden dañar su dispositivo o datos. Siempre debe escanearlo para detectar cualquier amenaza antes de usarlo. </p>
82
- <h3>Q: Cómo desinstalar Air Offense Command Mod APK? </h3>
83
- <p>A: Para desinstalar Air Offense Command Mod APK de su dispositivo, puede seguir estos pasos:</p>
84
- <ol>
85
- <li>Ir a la configuración del dispositivo y toque en aplicaciones o aplicaciones.</li>
86
- <li> Encontrar y toque en Air Ofensiva Comando Mod APK de la lista de aplicaciones. </li>
87
- <li>Toque en Desinstalar y confirme su acción. </li>
88
- <li>Espere a que el proceso de desinstalación termine y reinicie su dispositivo. </li>
89
- <h3>Q: ¿Cómo contactar al desarrollador de Air Offense Command? </h3>
90
- <p>A: Si tiene alguna pregunta o comentario sobre la versión original de Air Offense Command, puede ponerse en contacto con el desarrollador a través del correo electrónico [email protected] o a través de su página de Facebook en https://www.facebook.com/ensitmedia/ Estarán encantados de saber de usted. </p> 64aa2da5cf<br />
91
- <br />
92
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/rich/jupyter.py DELETED
@@ -1,101 +0,0 @@
1
- from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Sequence
2
-
3
- if TYPE_CHECKING:
4
- from pip._vendor.rich.console import ConsoleRenderable
5
-
6
- from . import get_console
7
- from .segment import Segment
8
- from .terminal_theme import DEFAULT_TERMINAL_THEME
9
-
10
- if TYPE_CHECKING:
11
- from pip._vendor.rich.console import ConsoleRenderable
12
-
13
- JUPYTER_HTML_FORMAT = """\
14
- <pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace">{code}</pre>
15
- """
16
-
17
-
18
- class JupyterRenderable:
19
- """A shim to write html to Jupyter notebook."""
20
-
21
- def __init__(self, html: str, text: str) -> None:
22
- self.html = html
23
- self.text = text
24
-
25
- def _repr_mimebundle_(
26
- self, include: Sequence[str], exclude: Sequence[str], **kwargs: Any
27
- ) -> Dict[str, str]:
28
- data = {"text/plain": self.text, "text/html": self.html}
29
- if include:
30
- data = {k: v for (k, v) in data.items() if k in include}
31
- if exclude:
32
- data = {k: v for (k, v) in data.items() if k not in exclude}
33
- return data
34
-
35
-
36
- class JupyterMixin:
37
- """Add to an Rich renderable to make it render in Jupyter notebook."""
38
-
39
- __slots__ = ()
40
-
41
- def _repr_mimebundle_(
42
- self: "ConsoleRenderable",
43
- include: Sequence[str],
44
- exclude: Sequence[str],
45
- **kwargs: Any,
46
- ) -> Dict[str, str]:
47
- console = get_console()
48
- segments = list(console.render(self, console.options))
49
- html = _render_segments(segments)
50
- text = console._render_buffer(segments)
51
- data = {"text/plain": text, "text/html": html}
52
- if include:
53
- data = {k: v for (k, v) in data.items() if k in include}
54
- if exclude:
55
- data = {k: v for (k, v) in data.items() if k not in exclude}
56
- return data
57
-
58
-
59
- def _render_segments(segments: Iterable[Segment]) -> str:
60
- def escape(text: str) -> str:
61
- """Escape html."""
62
- return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
63
-
64
- fragments: List[str] = []
65
- append_fragment = fragments.append
66
- theme = DEFAULT_TERMINAL_THEME
67
- for text, style, control in Segment.simplify(segments):
68
- if control:
69
- continue
70
- text = escape(text)
71
- if style:
72
- rule = style.get_html_style(theme)
73
- text = f'<span style="{rule}">{text}</span>' if rule else text
74
- if style.link:
75
- text = f'<a href="{style.link}" target="_blank">{text}</a>'
76
- append_fragment(text)
77
-
78
- code = "".join(fragments)
79
- html = JUPYTER_HTML_FORMAT.format(code=code)
80
-
81
- return html
82
-
83
-
84
- def display(segments: Iterable[Segment], text: str) -> None:
85
- """Render segments to Jupyter."""
86
- html = _render_segments(segments)
87
- jupyter_renderable = JupyterRenderable(html, text)
88
- try:
89
- from IPython.display import display as ipython_display
90
-
91
- ipython_display(jupyter_renderable)
92
- except ModuleNotFoundError:
93
- # Handle the case where the Console has force_jupyter=True,
94
- # but IPython is not installed.
95
- pass
96
-
97
-
98
- def print(*args: Any, **kwargs: Any) -> None:
99
- """Proxy for Console print."""
100
- console = get_console()
101
- return console.print(*args, **kwargs)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Billyosoro/ESRGAN/tests/test_model.py DELETED
@@ -1,126 +0,0 @@
1
- import torch
2
- import yaml
3
- from basicsr.archs.rrdbnet_arch import RRDBNet
4
- from basicsr.data.paired_image_dataset import PairedImageDataset
5
- from basicsr.losses.losses import GANLoss, L1Loss, PerceptualLoss
6
-
7
- from realesrgan.archs.discriminator_arch import UNetDiscriminatorSN
8
- from realesrgan.models.realesrgan_model import RealESRGANModel
9
- from realesrgan.models.realesrnet_model import RealESRNetModel
10
-
11
-
12
- def test_realesrnet_model():
13
- with open('tests/data/test_realesrnet_model.yml', mode='r') as f:
14
- opt = yaml.load(f, Loader=yaml.FullLoader)
15
-
16
- # build model
17
- model = RealESRNetModel(opt)
18
- # test attributes
19
- assert model.__class__.__name__ == 'RealESRNetModel'
20
- assert isinstance(model.net_g, RRDBNet)
21
- assert isinstance(model.cri_pix, L1Loss)
22
- assert isinstance(model.optimizers[0], torch.optim.Adam)
23
-
24
- # prepare data
25
- gt = torch.rand((1, 3, 32, 32), dtype=torch.float32)
26
- kernel1 = torch.rand((1, 5, 5), dtype=torch.float32)
27
- kernel2 = torch.rand((1, 5, 5), dtype=torch.float32)
28
- sinc_kernel = torch.rand((1, 5, 5), dtype=torch.float32)
29
- data = dict(gt=gt, kernel1=kernel1, kernel2=kernel2, sinc_kernel=sinc_kernel)
30
- model.feed_data(data)
31
- # check dequeue
32
- model.feed_data(data)
33
- # check data shape
34
- assert model.lq.shape == (1, 3, 8, 8)
35
- assert model.gt.shape == (1, 3, 32, 32)
36
-
37
- # change probability to test if-else
38
- model.opt['gaussian_noise_prob'] = 0
39
- model.opt['gray_noise_prob'] = 0
40
- model.opt['second_blur_prob'] = 0
41
- model.opt['gaussian_noise_prob2'] = 0
42
- model.opt['gray_noise_prob2'] = 0
43
- model.feed_data(data)
44
- # check data shape
45
- assert model.lq.shape == (1, 3, 8, 8)
46
- assert model.gt.shape == (1, 3, 32, 32)
47
-
48
- # ----------------- test nondist_validation -------------------- #
49
- # construct dataloader
50
- dataset_opt = dict(
51
- name='Demo',
52
- dataroot_gt='tests/data/gt',
53
- dataroot_lq='tests/data/lq',
54
- io_backend=dict(type='disk'),
55
- scale=4,
56
- phase='val')
57
- dataset = PairedImageDataset(dataset_opt)
58
- dataloader = torch.utils.data.DataLoader(dataset=dataset, batch_size=1, shuffle=False, num_workers=0)
59
- assert model.is_train is True
60
- model.nondist_validation(dataloader, 1, None, False)
61
- assert model.is_train is True
62
-
63
-
64
- def test_realesrgan_model():
65
- with open('tests/data/test_realesrgan_model.yml', mode='r') as f:
66
- opt = yaml.load(f, Loader=yaml.FullLoader)
67
-
68
- # build model
69
- model = RealESRGANModel(opt)
70
- # test attributes
71
- assert model.__class__.__name__ == 'RealESRGANModel'
72
- assert isinstance(model.net_g, RRDBNet) # generator
73
- assert isinstance(model.net_d, UNetDiscriminatorSN) # discriminator
74
- assert isinstance(model.cri_pix, L1Loss)
75
- assert isinstance(model.cri_perceptual, PerceptualLoss)
76
- assert isinstance(model.cri_gan, GANLoss)
77
- assert isinstance(model.optimizers[0], torch.optim.Adam)
78
- assert isinstance(model.optimizers[1], torch.optim.Adam)
79
-
80
- # prepare data
81
- gt = torch.rand((1, 3, 32, 32), dtype=torch.float32)
82
- kernel1 = torch.rand((1, 5, 5), dtype=torch.float32)
83
- kernel2 = torch.rand((1, 5, 5), dtype=torch.float32)
84
- sinc_kernel = torch.rand((1, 5, 5), dtype=torch.float32)
85
- data = dict(gt=gt, kernel1=kernel1, kernel2=kernel2, sinc_kernel=sinc_kernel)
86
- model.feed_data(data)
87
- # check dequeue
88
- model.feed_data(data)
89
- # check data shape
90
- assert model.lq.shape == (1, 3, 8, 8)
91
- assert model.gt.shape == (1, 3, 32, 32)
92
-
93
- # change probability to test if-else
94
- model.opt['gaussian_noise_prob'] = 0
95
- model.opt['gray_noise_prob'] = 0
96
- model.opt['second_blur_prob'] = 0
97
- model.opt['gaussian_noise_prob2'] = 0
98
- model.opt['gray_noise_prob2'] = 0
99
- model.feed_data(data)
100
- # check data shape
101
- assert model.lq.shape == (1, 3, 8, 8)
102
- assert model.gt.shape == (1, 3, 32, 32)
103
-
104
- # ----------------- test nondist_validation -------------------- #
105
- # construct dataloader
106
- dataset_opt = dict(
107
- name='Demo',
108
- dataroot_gt='tests/data/gt',
109
- dataroot_lq='tests/data/lq',
110
- io_backend=dict(type='disk'),
111
- scale=4,
112
- phase='val')
113
- dataset = PairedImageDataset(dataset_opt)
114
- dataloader = torch.utils.data.DataLoader(dataset=dataset, batch_size=1, shuffle=False, num_workers=0)
115
- assert model.is_train is True
116
- model.nondist_validation(dataloader, 1, None, False)
117
- assert model.is_train is True
118
-
119
- # ----------------- test optimize_parameters -------------------- #
120
- model.feed_data(data)
121
- model.optimize_parameters(1)
122
- assert model.output.shape == (1, 3, 32, 32)
123
- assert isinstance(model.log_dict, dict)
124
- # check returned keys
125
- expected_keys = ['l_g_pix', 'l_g_percep', 'l_g_gan', 'l_d_real', 'out_d_real', 'l_d_fake', 'out_d_fake']
126
- assert set(expected_keys).issubset(set(model.log_dict.keys()))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/detectron2/docs/tutorials/datasets.md DELETED
@@ -1,214 +0,0 @@
1
- # Use Custom Datasets
2
-
3
- If you want to use a custom dataset while also reusing detectron2's data loaders,
4
- you will need to
5
-
6
- 1. Register your dataset (i.e., tell detectron2 how to obtain your dataset).
7
- 2. Optionally, register metadata for your dataset.
8
-
9
- Next, we explain the above two concepts in details.
10
-
11
- The [Colab Notebook](https://colab.research.google.com/drive/16jcaJoc6bCFAQ96jDe2HwtXj7BMD_-m5)
12
- has a working example of how to register and train on a dataset of custom formats.
13
-
14
-
15
- ### Register a Dataset
16
-
17
- To let detectron2 know how to obtain a dataset named "my_dataset", you will implement
18
- a function that returns the items in your dataset and then tell detectron2 about this
19
- function:
20
- ```python
21
- def get_dicts():
22
- ...
23
- return list[dict] in the following format
24
-
25
- from detectron2.data import DatasetCatalog
26
- DatasetCatalog.register("my_dataset", get_dicts)
27
- ```
28
-
29
- Here, the snippet associates a dataset "my_dataset" with a function that returns the data.
30
- The registration stays effective until the process exists.
31
-
32
- The function can processes data from its original format into either one of the following:
33
- 1. Detectron2's standard dataset dict, described below. This will work with many other builtin
34
- features in detectron2, so it's recommended to use it when it's sufficient for your task.
35
- 2. Your custom dataset dict. You can also returns arbitrary dicts in your own format,
36
- such as adding extra keys for new tasks.
37
- Then you will need to handle them properly in the downstream as well.
38
- See below for more details.
39
-
40
- #### Standard Dataset Dicts
41
-
42
- For standard tasks
43
- (instance detection, instance/semantic/panoptic segmentation, keypoint detection),
44
- we load the original dataset into `list[dict]` with a specification similar to COCO's json annotations.
45
- This is our standard representation for a dataset.
46
-
47
- Each dict contains information about one image.
48
- The dict may have the following fields.
49
- The fields are often optional, and some functions may be able to
50
- infer certain fields from others if needed, e.g., the data loader
51
- will load the image from "file_name" and load "sem_seg" from "sem_seg_file_name".
52
-
53
- + `file_name`: the full path to the image file. Will apply rotation and flipping if the image has such exif information.
54
- + `sem_seg_file_name`: the full path to the ground truth semantic segmentation file.
55
- + `sem_seg`: semantic segmentation ground truth in a 2D `torch.Tensor`. Values in the array represent
56
- category labels starting from 0.
57
- + `height`, `width`: integer. The shape of image.
58
- + `image_id` (str or int): a unique id that identifies this image. Used
59
- during evaluation to identify the images, but a dataset may use it for different purposes.
60
- + `annotations` (list[dict]): each dict corresponds to annotations of one instance
61
- in this image. Images with empty `annotations` will by default be removed from training,
62
- but can be included using `DATALOADER.FILTER_EMPTY_ANNOTATIONS`.
63
- Each dict may contain the following keys:
64
- + `bbox` (list[float]): list of 4 numbers representing the bounding box of the instance.
65
- + `bbox_mode` (int): the format of bbox.
66
- It must be a member of
67
- [structures.BoxMode](../modules/structures.html#detectron2.structures.BoxMode).
68
- Currently supports: `BoxMode.XYXY_ABS`, `BoxMode.XYWH_ABS`.
69
- + `category_id` (int): an integer in the range [0, num_categories) representing the category label.
70
- The value num_categories is reserved to represent the "background" category, if applicable.
71
- + `segmentation` (list[list[float]] or dict):
72
- + If `list[list[float]]`, it represents a list of polygons, one for each connected component
73
- of the object. Each `list[float]` is one simple polygon in the format of `[x1, y1, ..., xn, yn]`.
74
- The Xs and Ys are either relative coordinates in [0, 1], or absolute coordinates,
75
- depend on whether "bbox_mode" is relative.
76
- + If `dict`, it represents the per-pixel segmentation mask in COCO's RLE format. The dict should have
77
- keys "size" and "counts". You can convert a uint8 segmentation mask of 0s and 1s into
78
- RLE format by `pycocotools.mask.encode(np.asarray(mask, order="F"))`.
79
- + `keypoints` (list[float]): in the format of [x1, y1, v1,..., xn, yn, vn].
80
- v[i] means the [visibility](http://cocodataset.org/#format-data) of this keypoint.
81
- `n` must be equal to the number of keypoint categories.
82
- The Xs and Ys are either relative coordinates in [0, 1], or absolute coordinates,
83
- depend on whether "bbox_mode" is relative.
84
-
85
- Note that the coordinate annotations in COCO format are integers in range [0, H-1 or W-1].
86
- By default, detectron2 adds 0.5 to absolute keypoint coordinates to convert them from discrete
87
- pixel indices to floating point coordinates.
88
- + `iscrowd`: 0 or 1. Whether this instance is labeled as COCO's "crowd
89
- region". Don't include this field if you don't know what it means.
90
-
91
- The following keys are used by Fast R-CNN style training, which is rare today.
92
-
93
- + `proposal_boxes` (array): 2D numpy array with shape (K, 4) representing K precomputed proposal boxes for this image.
94
- + `proposal_objectness_logits` (array): numpy array with shape (K, ), which corresponds to the objectness
95
- logits of proposals in 'proposal_boxes'.
96
- + `proposal_bbox_mode` (int): the format of the precomputed proposal bbox.
97
- It must be a member of
98
- [structures.BoxMode](../modules/structures.html#detectron2.structures.BoxMode).
99
- Default is `BoxMode.XYXY_ABS`.
100
-
101
-
102
- If your dataset is already a json file in COCO format, you can simply register it by
103
- ```python
104
- from detectron2.data.datasets import register_coco_instances
105
- register_coco_instances("my_dataset", {}, "json_annotation.json", "path/to/image/dir")
106
- ```
107
- which will take care of everything (including metadata) for you.
108
-
109
- If your dataset is in COCO format with custom per-instance annotations,
110
- the [load_coco_json](../modules/data.html#detectron2.data.datasets.load_coco_json) function can be used.
111
-
112
- #### Custom Dataset Dicts
113
-
114
- In the `list[dict]` that your dataset function return, the dictionary can also has arbitrary custom data.
115
- This can be useful when you're doing a new task and needs extra information not supported
116
- by the standard dataset dicts. In this case, you need to make sure the downstream code can handle your data
117
- correctly. Usually this requires writing a new `mapper` for the dataloader (see [Use Custom Dataloaders](data_loading.html))
118
-
119
- When designing your custom format, note that all dicts are stored in memory
120
- (sometimes serialized and with multiple copies).
121
- To save memory, each dict is meant to contain small but sufficient information
122
- about each sample, such as file names and annotations.
123
- Loading full samples typically happens in the data loader.
124
-
125
- For attributes shared among the entire dataset, use `Metadata` (see below).
126
- To avoid exmemory, do not save such information repeatly for each sample.
127
-
128
-
129
- ### "Metadata" for Datasets
130
-
131
- Each dataset is associated with some metadata, accessible through
132
- `MetadataCatalog.get(dataset_name).some_metadata`.
133
- Metadata is a key-value mapping that contains information that's shared among
134
- the entire dataset, and usually is used to interpret what's in the dataset, e.g.,
135
- names of classes, colors of classes, root of files, etc.
136
- This information will be useful for augmentation, evaluation, visualization, logging, etc.
137
- The structure of metadata depends on the what is needed from the corresponding downstream code.
138
-
139
-
140
- If you register a new dataset through `DatasetCatalog.register`,
141
- you may also want to add its corresponding metadata through
142
- `MetadataCatalog.get(dataset_name).set(name, value)`, to enable any features that need metadata.
143
- You can do it like this (using the metadata field "thing_classes" as an example):
144
-
145
- ```python
146
- from detectron2.data import MetadataCatalog
147
- MetadataCatalog.get("my_dataset").thing_classes = ["person", "dog"]
148
- ```
149
-
150
- Here is a list of metadata keys that are used by builtin features in detectron2.
151
- If you add your own dataset without these metadata, some features may be
152
- unavailable to you:
153
-
154
- * `thing_classes` (list[str]): Used by all instance detection/segmentation tasks.
155
- A list of names for each instance/thing category.
156
- If you load a COCO format dataset, it will be automatically set by the function `load_coco_json`.
157
-
158
- * `thing_colors` (list[tuple(r, g, b)]): Pre-defined color (in [0, 255]) for each thing category.
159
- Used for visualization. If not given, random colors are used.
160
-
161
- * `stuff_classes` (list[str]): Used by semantic and panoptic segmentation tasks.
162
- A list of names for each stuff category.
163
-
164
- * `stuff_colors` (list[tuple(r, g, b)]): Pre-defined color (in [0, 255]) for each stuff category.
165
- Used for visualization. If not given, random colors are used.
166
-
167
- * `keypoint_names` (list[str]): Used by keypoint localization. A list of names for each keypoint.
168
-
169
- * `keypoint_flip_map` (list[tuple[str]]): Used by the keypoint localization task. A list of pairs of names,
170
- where each pair are the two keypoints that should be flipped if the image is
171
- flipped during augmentation.
172
- * `keypoint_connection_rules`: list[tuple(str, str, (r, g, b))]. Each tuple specifies a pair of keypoints
173
- that are connected and the color to use for the line between them when visualized.
174
-
175
- Some additional metadata that are specific to the evaluation of certain datasets (e.g. COCO):
176
-
177
- * `thing_dataset_id_to_contiguous_id` (dict[int->int]): Used by all instance detection/segmentation tasks in the COCO format.
178
- A mapping from instance class ids in the dataset to contiguous ids in range [0, #class).
179
- Will be automatically set by the function `load_coco_json`.
180
-
181
- * `stuff_dataset_id_to_contiguous_id` (dict[int->int]): Used when generating prediction json files for
182
- semantic/panoptic segmentation.
183
- A mapping from semantic segmentation class ids in the dataset
184
- to contiguous ids in [0, num_categories). It is useful for evaluation only.
185
-
186
- * `json_file`: The COCO annotation json file. Used by COCO evaluation for COCO-format datasets.
187
- * `panoptic_root`, `panoptic_json`: Used by panoptic evaluation.
188
- * `evaluator_type`: Used by the builtin main training script to select
189
- evaluator. No need to use it if you write your own main script.
190
- You can just provide the [DatasetEvaluator](../modules/evaluation.html#detectron2.evaluation.DatasetEvaluator)
191
- for your dataset directly in your main script.
192
-
193
- NOTE: For background on the concept of "thing" and "stuff", see
194
- [On Seeing Stuff: The Perception of Materials by Humans and Machines](http://persci.mit.edu/pub_pdfs/adelson_spie_01.pdf).
195
- In detectron2, the term "thing" is used for instance-level tasks,
196
- and "stuff" is used for semantic segmentation tasks.
197
- Both are used in panoptic segmentation.
198
-
199
-
200
- ### Update the Config for New Datasets
201
-
202
- Once you've registered the dataset, you can use the name of the dataset (e.g., "my_dataset" in
203
- example above) in `DATASETS.{TRAIN,TEST}`.
204
- There are other configs you might want to change to train or evaluate on new datasets:
205
-
206
- * `MODEL.ROI_HEADS.NUM_CLASSES` and `MODEL.RETINANET.NUM_CLASSES` are the number of thing classes
207
- for R-CNN and RetinaNet models.
208
- * `MODEL.ROI_KEYPOINT_HEAD.NUM_KEYPOINTS` sets the number of keypoints for Keypoint R-CNN.
209
- You'll also need to set [Keypoint OKS](http://cocodataset.org/#keypoints-eval)
210
- with `TEST.KEYPOINT_OKS_SIGMAS` for evaluation.
211
- * `MODEL.SEM_SEG_HEAD.NUM_CLASSES` sets the number of stuff classes for Semantic FPN & Panoptic FPN.
212
- * If you're training Fast R-CNN (with precomputed proposals), `DATASETS.PROPOSAL_FILES_{TRAIN,TEST}`
213
- need to match the datasts. The format of proposal files are documented
214
- [here](../modules/data.html#detectron2.data.load_proposals_into_dataset).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/detectron2/projects/DensePose/densepose/dataset_mapper.py DELETED
@@ -1,118 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
3
-
4
- import copy
5
- import torch
6
- from fvcore.common.file_io import PathManager
7
-
8
- from detectron2.data import MetadataCatalog
9
- from detectron2.data import detection_utils as utils
10
- from detectron2.data import transforms as T
11
-
12
- from .structures import DensePoseDataRelative, DensePoseList, DensePoseTransformData
13
-
14
-
15
- class DatasetMapper:
16
- """
17
- A customized version of `detectron2.data.DatasetMapper`
18
- """
19
-
20
- def __init__(self, cfg, is_train=True):
21
- self.tfm_gens = utils.build_transform_gen(cfg, is_train)
22
-
23
- # fmt: off
24
- self.img_format = cfg.INPUT.FORMAT
25
- self.mask_on = cfg.MODEL.MASK_ON
26
- self.keypoint_on = cfg.MODEL.KEYPOINT_ON
27
- self.densepose_on = cfg.MODEL.DENSEPOSE_ON
28
- assert not cfg.MODEL.LOAD_PROPOSALS, "not supported yet"
29
- # fmt: on
30
- if self.keypoint_on and is_train:
31
- # Flip only makes sense in training
32
- self.keypoint_hflip_indices = utils.create_keypoint_hflip_indices(cfg.DATASETS.TRAIN)
33
- else:
34
- self.keypoint_hflip_indices = None
35
-
36
- if self.densepose_on:
37
- densepose_transform_srcs = [
38
- MetadataCatalog.get(ds).densepose_transform_src
39
- for ds in cfg.DATASETS.TRAIN + cfg.DATASETS.TEST
40
- ]
41
- assert len(densepose_transform_srcs) > 0
42
- # TODO: check that DensePose transformation data is the same for
43
- # all the datasets. Otherwise one would have to pass DB ID with
44
- # each entry to select proper transformation data. For now, since
45
- # all DensePose annotated data uses the same data semantics, we
46
- # omit this check.
47
- densepose_transform_data_fpath = PathManager.get_local_path(densepose_transform_srcs[0])
48
- self.densepose_transform_data = DensePoseTransformData.load(
49
- densepose_transform_data_fpath
50
- )
51
-
52
- self.is_train = is_train
53
-
54
- def __call__(self, dataset_dict):
55
- """
56
- Args:
57
- dataset_dict (dict): Metadata of one image, in Detectron2 Dataset format.
58
-
59
- Returns:
60
- dict: a format that builtin models in detectron2 accept
61
- """
62
- dataset_dict = copy.deepcopy(dataset_dict) # it will be modified by code below
63
- image = utils.read_image(dataset_dict["file_name"], format=self.img_format)
64
- utils.check_image_size(dataset_dict, image)
65
-
66
- image, transforms = T.apply_transform_gens(self.tfm_gens, image)
67
- image_shape = image.shape[:2] # h, w
68
- dataset_dict["image"] = torch.as_tensor(image.transpose(2, 0, 1).astype("float32"))
69
-
70
- if not self.is_train:
71
- dataset_dict.pop("annotations", None)
72
- return dataset_dict
73
-
74
- for anno in dataset_dict["annotations"]:
75
- if not self.mask_on:
76
- anno.pop("segmentation", None)
77
- if not self.keypoint_on:
78
- anno.pop("keypoints", None)
79
-
80
- # USER: Implement additional transformations if you have other types of data
81
- # USER: Don't call transpose_densepose if you don't need
82
- annos = [
83
- self._transform_densepose(
84
- utils.transform_instance_annotations(
85
- obj, transforms, image_shape, keypoint_hflip_indices=self.keypoint_hflip_indices
86
- ),
87
- transforms,
88
- )
89
- for obj in dataset_dict.pop("annotations")
90
- if obj.get("iscrowd", 0) == 0
91
- ]
92
- instances = utils.annotations_to_instances(annos, image_shape)
93
-
94
- if len(annos) and "densepose" in annos[0]:
95
- gt_densepose = [obj["densepose"] for obj in annos]
96
- instances.gt_densepose = DensePoseList(gt_densepose, instances.gt_boxes, image_shape)
97
-
98
- dataset_dict["instances"] = instances[instances.gt_boxes.nonempty()]
99
- return dataset_dict
100
-
101
- def _transform_densepose(self, annotation, transforms):
102
- if not self.densepose_on:
103
- return annotation
104
-
105
- # Handle densepose annotations
106
- is_valid, reason_not_valid = DensePoseDataRelative.validate_annotation(annotation)
107
- if is_valid:
108
- densepose_data = DensePoseDataRelative(annotation, cleanup=True)
109
- densepose_data.apply_transform(transforms, self.densepose_transform_data)
110
- annotation["densepose"] = densepose_data
111
- else:
112
- # logger = logging.getLogger(__name__)
113
- # logger.debug("Could not load DensePose annotation: {}".format(reason_not_valid))
114
- DensePoseDataRelative.cleanup_annotation(annotation)
115
- # NOTE: annotations for certain instances may be unavailable.
116
- # 'None' is accepted by the DensePostList data structure.
117
- annotation["densepose"] = None
118
- return annotation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/CVPR/LIVE/model_download/yolov5_model_p6_all.sh DELETED
@@ -1,8 +0,0 @@
1
- cd ./yolov5
2
-
3
- # 下载YOLOv5模型
4
- wget -c -t 0 https://github.com/ultralytics/yolov5/releases/download/v6.1/yolov5n6.pt
5
- wget -c -t 0 https://github.com/ultralytics/yolov5/releases/download/v6.1/yolov5s6.pt
6
- wget -c -t 0 https://github.com/ultralytics/yolov5/releases/download/v6.1/yolov5m6.pt
7
- wget -c -t 0 https://github.com/ultralytics/yolov5/releases/download/v6.1/yolov5l6.pt
8
- wget -c -t 0 https://github.com/ultralytics/yolov5/releases/download/v6.1/yolov5x6.pt
 
 
 
 
 
 
 
 
 
spaces/CVPR/LIVE/thrust/internal/test/thrust_nightly.pl DELETED
@@ -1,600 +0,0 @@
1
- #! /usr/bin/perl
2
-
3
- ###############################################################################
4
- # Copyright (c) 2018 NVIDIA Corporation
5
- #
6
- # Licensed under the Apache License, Version 2.0 (the "License");
7
- # you may not use this file except in compliance with the License.
8
- # You may obtain a copy of the License at
9
- #
10
- # http://www.apache.org/licenses/LICENSE-2.0
11
- #
12
- # Unless required by applicable law or agreed to in writing, software
13
- # distributed under the License is distributed on an "AS IS" BASIS,
14
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
- # See the License for the specific language governing permissions and
16
- # limitations under the License.
17
- ###############################################################################
18
-
19
- use strict;
20
- use warnings;
21
-
22
- print(`perl --version`);
23
-
24
- use Getopt::Long;
25
- use Cwd;
26
- use Cwd "abs_path";
27
- use Config; # For signal names and numbers.
28
- use IPC::Open2;
29
- use File::Temp;
30
- use POSIX "strftime";
31
-
32
- my $have_time_hi_res = 0;
33
-
34
- if (eval { require Time::HiRes })
35
- {
36
- printf("#### CONFIG timestamp `gettimeofday`\n");
37
-
38
- import Time::HiRes "gettimeofday";
39
-
40
- $have_time_hi_res = 1;
41
- } else {
42
- printf("#### CONFIG timestamp `time`\n");
43
- }
44
-
45
- sub timestamp()
46
- {
47
- if ($have_time_hi_res) {
48
- return gettimeofday();
49
- } else {
50
- return time();
51
- }
52
- }
53
-
54
- my %CmdLineOption;
55
- my $arch = "";
56
- my $abi = "";
57
- my $os = "";
58
- my $build = "release";
59
- my $bin_path;
60
- my $filecheck_path;
61
- my $filecheck_data_path = "internal/test";
62
- my $timeout_min = 15;
63
-
64
- # https://stackoverflow.com/questions/29862178/name-of-signal-number-2
65
- my @sig_names;
66
- @sig_names[ split ' ', $Config{sig_num} ] = split ' ', $Config{sig_name};
67
- my %sig_nums;
68
- @sig_nums{ split ' ', $Config{sig_name} } = split ' ', $Config{sig_num};
69
-
70
- if (`uname` =~ m/CYGWIN/) {
71
- $os = "win32";
72
- } elsif ($^O eq "MSWin32") {
73
- $os = "win32";
74
- } else {
75
- $os = `uname`;
76
- chomp($os);
77
- }
78
-
79
- if ($os eq "win32") {
80
- $ENV{'PROCESSOR_ARCHITECTURE'} ||= "";
81
- $ENV{'PROCESSOR_ARCHITEW6432'} ||= "";
82
-
83
- if ((lc($ENV{PROCESSOR_ARCHITECTURE}) ne "x86") ||
84
- (lc($ENV{PROCESSOR_ARCHITECTURE}) eq "amd64") ||
85
- (lc($ENV{PROCESSOR_ARCHITEW6432}) eq "amd64")) {
86
- $arch = "x86_64";
87
- } else {
88
- $arch = "i686";
89
- }
90
- } else {
91
- $arch = `uname -m`;
92
- chomp($arch);
93
- }
94
-
95
- sub usage()
96
- {
97
- printf("Usage: thrust_nightly.pl <options>\n");
98
- printf("Options:\n");
99
- printf(" -help : Print help message\n");
100
- printf(" -forcearch <arch> : i686|x86_64|ARMv7|aarch64 (default: $arch)\n");
101
- printf(" -forceabi <abi> : Specify abi to be used for arm (gnueabi|gnueabihf)\n");
102
- printf(" -forceos <os> : win32|Linux|Darwin (default: $os)\n");
103
- printf(" -build <release|debug> : (default: debug)\n");
104
- printf(" -bin-path <path> : Specify location of test binaries\n");
105
- printf(" -filecheck-path <path> : Specify location of filecheck binary\n");
106
- printf(" -filecheck-data-path <path> : Specify location of filecheck data (default: $filecheck_data_path)\n");
107
- printf(" -timeout-min <min> : timeout in minutes for each individual test\n");
108
- }
109
-
110
- GetOptions(\%CmdLineOption,
111
- 'help' => sub { usage() and exit 0 },
112
- "forcearch=s" => \$arch,
113
- "forceabi=s" => \$abi,
114
- "forceos=s" => \$os,
115
- "build=s" => \$build,
116
- "bin-path=s" => \$bin_path,
117
- "filecheck-path=s" => \$filecheck_path,
118
- "filecheck-data-path=s" => \$filecheck_data_path,
119
- "timeout-min=i" => \$timeout_min,
120
- );
121
-
122
- my $pwd = getcwd();
123
- my $bin_path_root = abs_path ("${pwd}/..");
124
-
125
- if ($arch eq "ARMv7") {
126
- if ($abi eq "") {
127
- $abi = "_gnueabi"; #Use default abi for arm if not specified
128
- }
129
- else {
130
- $abi = "_${abi}";
131
- }
132
- }
133
- else {
134
- $abi = ""; #Ignore abi for architectures other than arm
135
- }
136
-
137
- my $uname = "";
138
- $uname = $arch;
139
- chomp($uname);
140
-
141
- if (not $bin_path) {
142
- $bin_path = "${bin_path_root}/bin/${uname}_${os}${abi}_${build}";
143
- }
144
-
145
- if (not $filecheck_path) {
146
- $filecheck_path = "${bin_path}/nvvm/tools";
147
- }
148
-
149
- sub process_return_code {
150
- my ($name, $ret, $msg) = @_;
151
-
152
- if ($ret != 0) {
153
- my $signal = $ret & 127;
154
- my $app_exit = $ret >> 8;
155
- my $dumped_core = $ret & 0x80;
156
- if (($app_exit != 0) && ($app_exit != 0)) {
157
- if ($msg ne "") {
158
- printf("#### ERROR $name exited with return value $app_exit. $msg\n");
159
- } else {
160
- printf("#### ERROR $name exited with return value $app_exit.\n");
161
- }
162
- }
163
- if ($signal != 0) {
164
- if ($msg ne "") {
165
- printf("#### ERROR $name received signal SIG$sig_names[$signal] ($signal). $msg\n");
166
- } else {
167
- printf("#### ERROR $name received signal SIG$sig_names[$signal] ($signal).\n");
168
- }
169
- if ($sig_nums{'INT'} eq $signal) {
170
- die("Terminating testing due to SIGINT.");
171
- }
172
- }
173
- if ($dumped_core != 0) {
174
- if ($msg ne "") {
175
- printf("#### ERROR $name generated a core dump. $msg\n");
176
- } else {
177
- printf("#### ERROR $name generated a core dump.\n");
178
- }
179
- }
180
- }
181
- }
182
-
183
- my $have_filecheck = 1;
184
-
185
- sub filecheck_sanity {
186
- my $filecheck_cmd = "$filecheck_path/FileCheck $filecheck_data_path/thrust.sanity.filecheck";
187
-
188
- my $filecheck_pid = open(my $filecheck_stdin, "|-", "$filecheck_cmd 2>&1");
189
-
190
- print $filecheck_stdin "SANITY";
191
-
192
- my $filecheck_ret = 0;
193
- if (close($filecheck_stdin) == 0)
194
- {
195
- $filecheck_ret = $?;
196
- }
197
-
198
- if ($filecheck_ret == 0) {
199
- printf("#### SANE FileCheck\n");
200
- } else {
201
- # Use a temporary file to send the output to
202
- # FileCheck so we can get the output this time,
203
- # because Perl and bidirectional pipes suck.
204
- my $tmp = File::Temp->new();
205
- my $tmp_filename = $tmp->filename;
206
- print $tmp "SANITY";
207
-
208
- printf("********************************************************************************\n");
209
- print `$filecheck_cmd -input-file $tmp_filename`;
210
- printf("********************************************************************************\n");
211
-
212
- process_return_code("FileCheck Sanity", $filecheck_ret, "");
213
- printf("#### INSANE FileCheck\n");
214
-
215
- $have_filecheck = 0;
216
- }
217
- }
218
-
219
- # Wrapper for system that logs the commands so you can see what it did
220
- sub run_cmd {
221
- my ($cmd) = @_;
222
- my $ret = 0;
223
- my @executable;
224
- my @output;
225
- my $syst_cmd;
226
-
227
- my $start = timestamp();
228
- eval {
229
- local $SIG{ALRM} = sub { die("Command timed out (received SIGALRM).\n") };
230
- alarm (60 * $timeout_min);
231
- $syst_cmd = $cmd;
232
-
233
- @executable = split(' ', $syst_cmd, 2);
234
-
235
- open(my $child, "-|", "$syst_cmd") or die("Could not execute $syst_cmd.\n");
236
-
237
- if ($child)
238
- {
239
- @output = <$child>;
240
- }
241
-
242
- if (close($child) == 0)
243
- {
244
- $ret = $?;
245
- }
246
-
247
- alarm 0;
248
- };
249
- my $elapsed = timestamp() - $start;
250
-
251
- if ($@) {
252
- printf("\n#### ERROR Command timeout reached, killing $executable[0].\n");
253
- system("killall ".$executable[0]);
254
- return ($sig_nums{'KILL'}, $elapsed, @output);
255
- }
256
-
257
- return ($ret, $elapsed, @output);
258
- }
259
-
260
- sub current_time
261
- {
262
- return strftime("%x %X %Z", localtime());
263
- }
264
-
265
- my $failures = 0;
266
- my $known_failures = 0;
267
- my $errors = 0;
268
- my $passes = 0;
269
-
270
- sub run_examples {
271
- # Get list of tests in binary folder.
272
- my $dir = cwd();
273
- chdir $bin_path;
274
- my @examplelist;
275
- if ($os eq "win32")
276
- {
277
- @examplelist = glob('thrust.example.*.exe');
278
- } else {
279
- @examplelist = glob('thrust.example.*');
280
- }
281
-
282
- chdir $dir;
283
-
284
- my $test;
285
- foreach $test (@examplelist)
286
- {
287
- my $test_exe = $test;
288
-
289
- # Ignore FileCheck files.
290
- if ($test =~ /[.]filecheck$/)
291
- {
292
- next;
293
- }
294
-
295
- if ($os eq "win32")
296
- {
297
- $test =~ s/\.exe//g;
298
- }
299
-
300
- # Check the test actually exists.
301
- if (!-e "${bin_path}/${test_exe}")
302
- {
303
- next;
304
- }
305
-
306
- my $cmd = "${bin_path}/${test_exe} --verbose 2>&1";
307
-
308
- printf("&&&& RUNNING $test\n");
309
- printf("#### CURRENT_TIME " . current_time() . "\n");
310
-
311
- my ($ret, $elapsed, @output) = run_cmd($cmd);
312
-
313
- printf("********************************************************************************\n");
314
- print @output;
315
- printf("********************************************************************************\n");
316
-
317
- if ($ret != 0) {
318
- process_return_code($test, $ret, "Example crash?");
319
- printf("&&&& FAILED $test\n");
320
- printf("#### WALLTIME $test %.2f [s]\n", $elapsed);
321
- $errors = $errors + 1;
322
- } else {
323
- printf("&&&& PASSED $test\n");
324
- printf("#### WALLTIME $test %.2f [s]\n", $elapsed);
325
- $passes = $passes + 1;
326
-
327
- if ($have_filecheck) {
328
- # Check output with LLVM FileCheck.
329
-
330
- printf("&&&& RUNNING FileCheck $test\n");
331
-
332
- if (-f "${filecheck_data_path}/${test}.filecheck") {
333
- # If the filecheck file is empty, don't use filecheck, just
334
- # check if the output file is also empty.
335
- if (-z "${filecheck_data_path}/${test}.filecheck") {
336
- if (join("", @output) eq "") {
337
- printf("&&&& PASSED FileCheck $test\n");
338
- $passes = $passes + 1;
339
- } else {
340
- printf("#### ERROR Output received but not expected.\n");
341
- printf("&&&& FAILED FileCheck $test\n");
342
- $failures = $failures + 1;
343
- }
344
- } else {
345
- my $filecheck_cmd = "$filecheck_path/FileCheck $filecheck_data_path/$test.filecheck";
346
-
347
- my $filecheck_pid = open(my $filecheck_stdin, "|-", "$filecheck_cmd 2>&1");
348
-
349
- print $filecheck_stdin @output;
350
-
351
- my $filecheck_ret = 0;
352
- if (close($filecheck_stdin) == 0)
353
- {
354
- $filecheck_ret = $?;
355
- }
356
-
357
- if ($filecheck_ret == 0) {
358
- printf("&&&& PASSED FileCheck $test\n");
359
- $passes = $passes + 1;
360
- } else {
361
- # Use a temporary file to send the output to
362
- # FileCheck so we can get the output this time,
363
- # because Perl and bidirectional pipes suck.
364
- my $tmp = File::Temp->new();
365
- my $tmp_filename = $tmp->filename;
366
- print $tmp @output;
367
-
368
- printf("********************************************************************************\n");
369
- print `$filecheck_cmd -input-file $tmp_filename`;
370
- printf("********************************************************************************\n");
371
-
372
- process_return_code("FileCheck $test", $filecheck_ret, "");
373
- printf("&&&& FAILED FileCheck $test\n");
374
- $failures = $failures + 1;
375
- }
376
- }
377
- } else {
378
- printf("#### ERROR $test has no FileCheck comparison.\n");
379
- printf("&&&& FAILED FileCheck $test\n");
380
- $errors = $errors + 1;
381
- }
382
- }
383
- }
384
- printf("\n");
385
- }
386
- }
387
-
388
- sub run_unit_tests {
389
- # Get list of tests in binary folder.
390
- my $dir = cwd();
391
- chdir $bin_path;
392
- my @unittestlist;
393
- if ($os eq "win32")
394
- {
395
- @unittestlist = glob('thrust.test.*.exe');
396
- } else {
397
- @unittestlist = glob('thrust.test.*');
398
- }
399
- chdir $dir;
400
-
401
- my $test;
402
- foreach $test (@unittestlist)
403
- {
404
- my $test_exe = $test;
405
-
406
- # Ignore FileCheck files.
407
- if ($test =~ /[.]filecheck$/)
408
- {
409
- next;
410
- }
411
-
412
- if ($os eq "win32")
413
- {
414
- $test =~ s/\.exe//g;
415
- }
416
-
417
- # Check the test actually exists.
418
- if (!-e "${bin_path}/${test_exe}")
419
- {
420
- next;
421
- }
422
-
423
- # Check the test actually exists
424
- next unless (-e "${bin_path}/${test_exe}");
425
-
426
- my $cmd = "${bin_path}/${test_exe} --verbose 2>&1";
427
-
428
- printf("&&&& RUNNING $test\n");
429
- printf("#### CURRENT_TIME " . current_time() . "\n");
430
-
431
- my ($ret, $elapsed, @output) = run_cmd($cmd);
432
-
433
- printf("********************************************************************************\n");
434
- print @output;
435
- printf("********************************************************************************\n");
436
- my $fail = 0;
437
- my $known_fail = 0;
438
- my $error = 0;
439
- my $pass = 0;
440
- my $found_totals = 0;
441
- foreach my $line (@output)
442
- {
443
- if (($fail, $known_fail, $error, $pass) = $line =~ /Totals: ([0-9]+) failures, ([0-9]+) known failures, ([0-9]+) errors, and ([0-9]+) passes[.]/igs) {
444
- $found_totals = 1;
445
- $failures = $failures + $fail;
446
- $known_failures = $known_failures + $known_fail;
447
- $errors = $errors + $error;
448
- $passes = $passes + $pass;
449
- last;
450
- } else {
451
- $fail = 0;
452
- $known_fail = 0;
453
- $error = 0;
454
- $pass = 0;
455
- }
456
- }
457
- if ($ret == 0) {
458
- if ($found_totals == 0) {
459
- $errors = $errors + 1;
460
- printf("#### ERROR $test returned 0 and no summary line was found. Invalid test?\n");
461
- printf("&&&& FAILED $test\n");
462
- printf("#### WALLTIME $test %.2f [s]\n", $elapsed);
463
- }
464
- else {
465
- if ($fail != 0 or $error != 0) {
466
- $errors = $errors + 1;
467
- printf("#### ERROR $test returned 0 and had failures or errors. Test driver error?\n");
468
- printf("&&&& FAILED $test\n");
469
- printf("#### WALLTIME $test %.2f [s]\n", $elapsed);
470
- } elsif ($known_fail == 0 and $pass == 0) {
471
- printf("#### DISABLED $test returned 0 and had no failures, known failures, errors or passes.\n");
472
- printf("&&&& PASSED $test\n");
473
- printf("#### WALLTIME $test %.2f [s]\n", $elapsed);
474
- } else {
475
- printf("&&&& PASSED $test\n");
476
- printf("#### WALLTIME $test %.2f [s]\n", $elapsed);
477
-
478
- if ($have_filecheck) {
479
- # Check output with LLVM FileCheck if the test has a FileCheck input.
480
-
481
- if (-f "${filecheck_data_path}/${test}.filecheck") {
482
- printf("&&&& RUNNING FileCheck $test\n");
483
-
484
- # If the filecheck file is empty, don't use filecheck,
485
- # just check if the output file is also empty.
486
- if (! -z "${filecheck_data_path}/${test}.filecheck") {
487
- if (@output) {
488
- printf("&&&& PASSED FileCheck $test\n");
489
- $passes = $passes + 1;
490
- } else {
491
- printf("#### Output received but not expected.\n");
492
- printf("&&&& FAILED FileCheck $test\n");
493
- $failures = $failures + 1;
494
- }
495
- } else {
496
- my $filecheck_cmd = "$filecheck_path/FileCheck $filecheck_data_path/$test.filecheck";
497
-
498
- my $filecheck_pid = open(my $filecheck_stdin, "|-", "$filecheck_cmd 2>&1");
499
-
500
- print $filecheck_stdin @output;
501
-
502
- my $filecheck_ret = 0;
503
- if (close($filecheck_stdin) == 0)
504
- {
505
- $filecheck_ret = $?;
506
- }
507
-
508
- if ($filecheck_ret == 0) {
509
- printf("&&&& PASSED FileCheck $test\n");
510
- $passes = $passes + 1;
511
- } else {
512
- # Use a temporary file to send the output to
513
- # FileCheck so we can get the output this time,
514
- # because Perl and bidirectional pipes suck.
515
- my $tmp = File::Temp->new();
516
- my $tmp_filename = $tmp->filename;
517
- print $tmp @output;
518
-
519
- printf("********************************************************************************\n");
520
- print `$filecheck_cmd -input-file $tmp_filename`;
521
- printf("********************************************************************************\n");
522
-
523
- process_return_code("FileCheck $test", $filecheck_ret, "");
524
- printf("&&&& FAILED FileCheck $test\n");
525
- $failures = $failures + 1;
526
- }
527
- }
528
- }
529
- }
530
- }
531
- }
532
- } else {
533
- $errors = $errors + 1;
534
- process_return_code($test, $ret, "Test crash?");
535
- printf("&&&& FAILED $test\n");
536
- printf("#### WALLTIME $test %.2f [s]\n", $elapsed);
537
- }
538
- printf("\n");
539
- }
540
- }
541
-
542
- sub dvs_summary {
543
- my $dvs_score = 0;
544
- my $denominator = $failures + $known_failures + $errors + $passes;
545
- if ($denominator == 0) {
546
- $dvs_score = 0;
547
- }
548
- else {
549
- $dvs_score = 100 * (($passes + $known_failures) / $denominator);
550
- }
551
-
552
- printf("\n");
553
-
554
- printf("%*%*%*%* FA!LUR3S $failures\n");
555
- printf("%*%*%*%* KN0WN FA!LUR3S $known_failures\n");
556
- printf("%*%*%*%* 3RR0RS $errors\n");
557
- printf("%*%*%*%* PASS3S $passes\n");
558
-
559
- printf("\n");
560
-
561
- printf("CUDA DVS BASIC SANITY SCORE : %.1f\n", $dvs_score);
562
-
563
- if ($failures + $errors > 0) {
564
- exit(1);
565
- }
566
- }
567
-
568
- ###############################################################################
569
-
570
- printf("#### CONFIG arch `%s`\n", $arch);
571
- printf("#### CONFIG abi `%s`\n", $abi);
572
- printf("#### CONFIG os `%s`\n", $os);
573
- printf("#### CONFIG build `%s`\n", $build);
574
- printf("#### CONFIG bin_path `%s`\n", $bin_path);
575
- printf("#### CONFIG have_filecheck `$have_filecheck`\n");
576
- printf("#### CONFIG filecheck_path `%s`\n", $filecheck_path);
577
- printf("#### CONFIG filecheck_data_path `%s`\n", $filecheck_data_path);
578
- printf("#### CONFIG have_time_hi_res `$have_time_hi_res`\n");
579
- printf("#### CONFIG timeout_min `%s`\n", $timeout_min);
580
- printf("#### ENV PATH `%s`\n", defined $ENV{'PATH'} ? $ENV{'PATH'} : '');
581
- printf("#### ENV LD_LIBRARY_PATH `%s`\n", defined $ENV{'LD_LIBRARY_PATH'} ? $ENV{'LD_LIBRARY_PATH'} : '');
582
-
583
- printf("\n");
584
-
585
- filecheck_sanity();
586
-
587
- printf("\n");
588
-
589
- my $START_TIME = current_time();
590
-
591
- run_examples();
592
- run_unit_tests();
593
-
594
- my $STOP_TIME = current_time();
595
-
596
- printf("#### START_TIME $START_TIME\n");
597
- printf("#### STOP_TIME $STOP_TIME\n");
598
-
599
- dvs_summary();
600
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/CVPR/LIVE/thrust/thrust/detail/type_traits/iterator/is_output_iterator.h DELETED
@@ -1,66 +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/detail/type_traits.h>
21
- #include <thrust/detail/type_traits/is_metafunction_defined.h>
22
- #include <thrust/iterator/iterator_traits.h>
23
- #include <thrust/iterator/detail/any_assign.h>
24
-
25
- namespace thrust
26
- {
27
-
28
- namespace detail
29
- {
30
-
31
-
32
- template<typename T>
33
- struct is_void_like
34
- : thrust::detail::or_<
35
- thrust::detail::is_void<T>,
36
- thrust::detail::is_same<T,thrust::detail::any_assign>
37
- >
38
- {}; // end is_void_like
39
-
40
-
41
- template<typename T>
42
- struct lazy_is_void_like
43
- : is_void_like<typename T::type>
44
- {}; // end lazy_is_void_like
45
-
46
-
47
- // XXX this meta function should first check that T is actually an iterator
48
- //
49
- // if thrust::iterator_value<T> is defined and thrust::iterator_value<T>::type == void
50
- // return false
51
- // else
52
- // return true
53
- template<typename T>
54
- struct is_output_iterator
55
- : eval_if<
56
- is_metafunction_defined<thrust::iterator_value<T> >::value,
57
- lazy_is_void_like<thrust::iterator_value<T> >,
58
- thrust::detail::true_type
59
- >::type
60
- {
61
- }; // end is_output_iterator
62
-
63
- } // end detail
64
-
65
- } // end thrust
66
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/CVPR/LIVE/thrust/thrust/system/cpp/detail/extrema.h DELETED
@@ -1,23 +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
-
21
- // this system inherits extrema algorithms
22
- #include <thrust/system/detail/sequential/extrema.h>
23
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Chaitanya01/InvestingPlatform/setup.sh DELETED
@@ -1,13 +0,0 @@
1
- mkdir -p ~/.streamlit/
2
-
3
- echo "\
4
- [general]\n\
5
- email = \"[email protected]\"\n\
6
- " > ~/.streamlit/credentials.toml
7
-
8
- echo "\
9
- [server]\n\
10
- headless = true\n\
11
- enableCORS=false\n\
12
- port = $PORT\n\
13
- " > ~/.streamlit/config.toml
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Chomkwoy/Nilkessye/cpool_new/setup.py DELETED
@@ -1,14 +0,0 @@
1
- from setuptools import setup
2
- from torch.utils.cpp_extension import BuildExtension, CppExtension
3
-
4
- setup(name="cpools",
5
- ext_modules=[
6
- CppExtension("top_pool", ["src/top_pool.cpp"]),
7
- CppExtension("bottom_pool", ["src/bottom_pool.cpp"]),
8
- CppExtension("left_pool", ["src/left_pool.cpp"]),
9
- CppExtension("right_pool", ["src/right_pool.cpp"])
10
- ],
11
- cmdclass={
12
- "build_ext": BuildExtension
13
- }
14
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/ChristopherMarais/Andrew_AI-BB_classification-beta/mysite/andrew_alpha/admin.py DELETED
@@ -1,3 +0,0 @@
1
- from django.contrib import admin
2
-
3
- # Register your models here.
 
 
 
 
spaces/CognitiveLabs/Research-Assistant/statics/style.py DELETED
@@ -1,117 +0,0 @@
1
- css = """
2
- .top-bar {
3
- padding-bottom: 10px;
4
- background-color: transparent;
5
- }
6
-
7
- .top-bar .in-bar-title {
8
- background-image: linear-gradient(45deg, #8B5FBF, #D6C6E1, #ffffff);
9
- -webkit-background-clip: text;
10
- background-clip: text;
11
- -webkit-text-fill-color: transparent;
12
- font-family: Gelion, "Open Sans", Helvetica, "Helvetica Neue", Arial;
13
- font-size: 2rem;
14
- font-weight: bold;
15
- text-align: left;
16
- display: block;
17
- }
18
-
19
- .top-bar .in-bar-subtitle {
20
- font-family: 'Crimson Pro';
21
- color: #878787;
22
- font-size: 1.4rem;
23
- margin-top: -5px;
24
- display: block;
25
- }
26
-
27
- .main {
28
- max-width: 800px;
29
- min-width: min(100%, 800px);
30
- align-self: center;
31
- }
32
-
33
- .output {
34
- padding: 10px;
35
- min-height: 300px;
36
- border: 1.5px solid #AC7DD280;
37
- border-radius: 10px;
38
- margin-bottom: 10px;
39
- transition: opacity .1s ease-in-out;
40
- background: var(--block-background-fill);
41
- }
42
-
43
- #history {
44
- padding: 10px !important;
45
- border: 1.5px dashed #AC7DD2 !important;
46
- border-radius: 10px !important;
47
- }
48
-
49
- #primary-btn {
50
- border: 1.5px solid #AC7DD2;
51
- font-size: 20px;
52
- }
53
-
54
- summary {
55
- font-size: 14px;
56
- font-weight: bold;
57
- }
58
-
59
- #history_box {
60
- border-bottom: 1.5px dashed #9A73B5;
61
- padding: 10px;
62
- }
63
-
64
- .tab-nav {
65
- border-bottom: 1.5px solid #9A73B5 !important;
66
- }
67
-
68
- button.selected {
69
- border: 1.5px solid #9A73B5 !important;
70
- border-bottom: none !important;
71
- }
72
-
73
- .tabitem {
74
- border: 1.5px solid #9A73B5 !important;
75
- border-top: none !important;
76
- }
77
- """
78
-
79
- # #809A73B5
80
-
81
- top_bar = """
82
- <head>
83
- <link rel="preconnect" href="https://fonts.googleapis.com">
84
- <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
85
- <link href="https://fonts.googleapis.com/css2?family=Crimson+Pro:[email protected]&display=swap" rel="stylesheet">
86
- <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.1/css/all.css">
87
- </head>
88
- <body>
89
- <div class="top-bar">
90
- <div class="top-bar-left">
91
- <span class="in-bar-title">
92
- AI Research Assistant
93
- <a href="https://github.com/paradoxtown/AI-Research-Assistant">
94
- <i class="fab fa-github" style="font-size:25px;"></i>
95
- </a>
96
- </span>
97
- <span class="in-bar-subtitle">Your personal free GPT researcher</span>
98
- </div>
99
- </div>
100
- <body>
101
- """
102
-
103
- report_html = """
104
- <span data-testid="block-info" class="svelte-1gfkn6j custom_label")># Report</span>
105
- """
106
-
107
- english_polishing_html = """
108
- <span data-testid="block-info" class="svelte-1gfkn6j custom_label")># Polished Result</span>
109
- """
110
-
111
- history_result_html = """
112
- <span data-testid="block-info" class="svelte-1gfkn6j custom_label")># History Result</span>
113
- """
114
-
115
- literature_review_html = """
116
- <span data-testid="block-info" class="svelte-1gfkn6j custom_label")>under construction...</span>
117
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Cong723/gpt-academic-public/crazy_functions/test_project/python/dqn/__init__.py DELETED
@@ -1,2 +0,0 @@
1
- from stable_baselines3.dqn.dqn import DQN
2
- from stable_baselines3.dqn.policies import CnnPolicy, MlpPolicy
 
 
 
spaces/Cropinky/gpt2-rap-songs/README.md DELETED
@@ -1,33 +0,0 @@
1
- ---
2
- title: Gpt2 Rap Song generator
3
- emoji: 🎤
4
- colorFrom: red
5
- colorTo: black
6
- sdk: streamlit
7
- app_file: app.py
8
- pinned: true
9
- ---
10
-
11
- # Configuration
12
-
13
- `title`: _string_
14
- Display title for the Space
15
-
16
- `emoji`: _string_
17
- Space emoji (emoji-only character allowed)
18
-
19
- `colorFrom`: _string_
20
- Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray)
21
-
22
- `colorTo`: _string_
23
- Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray)
24
-
25
- `sdk`: _string_
26
- Can be either `gradio` or `streamlit`
27
-
28
- `app_file`: _string_
29
- Path to your main application file (which contains either `gradio` or `streamlit` Python code).
30
- Path is relative to the root of the repository.
31
-
32
- `pinned`: _boolean_
33
- Whether the Space stays on top of your list.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/gradio/processing_utils.py DELETED
@@ -1,546 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import base64
4
- import json
5
- import logging
6
- import os
7
- import shutil
8
- import subprocess
9
- import tempfile
10
- import warnings
11
- from io import BytesIO
12
- from pathlib import Path
13
-
14
- import numpy as np
15
- from gradio_client import utils as client_utils
16
- from PIL import Image, ImageOps, PngImagePlugin
17
-
18
- from gradio import wasm_utils
19
-
20
- if not wasm_utils.IS_WASM:
21
- # TODO: Support ffmpeg on Wasm
22
- from ffmpy import FFmpeg, FFprobe, FFRuntimeError
23
-
24
- with warnings.catch_warnings():
25
- warnings.simplefilter("ignore") # Ignore pydub warning if ffmpeg is not installed
26
- from pydub import AudioSegment
27
-
28
- log = logging.getLogger(__name__)
29
-
30
- #########################
31
- # GENERAL
32
- #########################
33
-
34
-
35
- def to_binary(x: str | dict) -> bytes:
36
- """Converts a base64 string or dictionary to a binary string that can be sent in a POST."""
37
- if isinstance(x, dict):
38
- if x.get("data"):
39
- base64str = x["data"]
40
- else:
41
- base64str = client_utils.encode_url_or_file_to_base64(x["name"])
42
- else:
43
- base64str = x
44
- return base64.b64decode(extract_base64_data(base64str))
45
-
46
-
47
- def extract_base64_data(x: str) -> str:
48
- """Just extracts the base64 data from a general base64 string."""
49
- return x.rsplit(",", 1)[-1]
50
-
51
-
52
- #########################
53
- # IMAGE PRE-PROCESSING
54
- #########################
55
-
56
-
57
- def decode_base64_to_image(encoding: str) -> Image.Image:
58
- image_encoded = extract_base64_data(encoding)
59
- img = Image.open(BytesIO(base64.b64decode(image_encoded)))
60
- try:
61
- if hasattr(ImageOps, "exif_transpose"):
62
- img = ImageOps.exif_transpose(img)
63
- except Exception:
64
- log.warning(
65
- "Failed to transpose image %s based on EXIF data.",
66
- img,
67
- exc_info=True,
68
- )
69
- return img
70
-
71
-
72
- def encode_plot_to_base64(plt):
73
- with BytesIO() as output_bytes:
74
- plt.savefig(output_bytes, format="png")
75
- bytes_data = output_bytes.getvalue()
76
- base64_str = str(base64.b64encode(bytes_data), "utf-8")
77
- return "data:image/png;base64," + base64_str
78
-
79
-
80
- def get_pil_metadata(pil_image):
81
- # Copy any text-only metadata
82
- metadata = PngImagePlugin.PngInfo()
83
- for key, value in pil_image.info.items():
84
- if isinstance(key, str) and isinstance(value, str):
85
- metadata.add_text(key, value)
86
-
87
- return metadata
88
-
89
-
90
- def encode_pil_to_bytes(pil_image, format="png"):
91
- with BytesIO() as output_bytes:
92
- pil_image.save(output_bytes, format, pnginfo=get_pil_metadata(pil_image))
93
- return output_bytes.getvalue()
94
-
95
-
96
- def encode_pil_to_base64(pil_image):
97
- bytes_data = encode_pil_to_bytes(pil_image)
98
- base64_str = str(base64.b64encode(bytes_data), "utf-8")
99
- return "data:image/png;base64," + base64_str
100
-
101
-
102
- def encode_array_to_base64(image_array):
103
- with BytesIO() as output_bytes:
104
- pil_image = Image.fromarray(_convert(image_array, np.uint8, force_copy=False))
105
- pil_image.save(output_bytes, "PNG")
106
- bytes_data = output_bytes.getvalue()
107
- base64_str = str(base64.b64encode(bytes_data), "utf-8")
108
- return "data:image/png;base64," + base64_str
109
-
110
-
111
- def resize_and_crop(img, size, crop_type="center"):
112
- """
113
- Resize and crop an image to fit the specified size.
114
- args:
115
- size: `(width, height)` tuple. Pass `None` for either width or height
116
- to only crop and resize the other.
117
- crop_type: can be 'top', 'middle' or 'bottom', depending on this
118
- value, the image will cropped getting the 'top/left', 'middle' or
119
- 'bottom/right' of the image to fit the size.
120
- raises:
121
- ValueError: if an invalid `crop_type` is provided.
122
- """
123
- if crop_type == "top":
124
- center = (0, 0)
125
- elif crop_type == "center":
126
- center = (0.5, 0.5)
127
- else:
128
- raise ValueError
129
-
130
- resize = list(size)
131
- if size[0] is None:
132
- resize[0] = img.size[0]
133
- if size[1] is None:
134
- resize[1] = img.size[1]
135
- return ImageOps.fit(img, resize, centering=center) # type: ignore
136
-
137
-
138
- ##################
139
- # Audio
140
- ##################
141
-
142
-
143
- def audio_from_file(filename, crop_min=0, crop_max=100):
144
- try:
145
- audio = AudioSegment.from_file(filename)
146
- except FileNotFoundError as e:
147
- isfile = Path(filename).is_file()
148
- msg = (
149
- f"Cannot load audio from file: `{'ffprobe' if isfile else filename}` not found."
150
- + " Please install `ffmpeg` in your system to use non-WAV audio file formats"
151
- " and make sure `ffprobe` is in your PATH."
152
- if isfile
153
- else ""
154
- )
155
- raise RuntimeError(msg) from e
156
- if crop_min != 0 or crop_max != 100:
157
- audio_start = len(audio) * crop_min / 100
158
- audio_end = len(audio) * crop_max / 100
159
- audio = audio[audio_start:audio_end]
160
- data = np.array(audio.get_array_of_samples())
161
- if audio.channels > 1:
162
- data = data.reshape(-1, audio.channels)
163
- return audio.frame_rate, data
164
-
165
-
166
- def audio_to_file(sample_rate, data, filename, format="wav"):
167
- if format == "wav":
168
- data = convert_to_16_bit_wav(data)
169
- audio = AudioSegment(
170
- data.tobytes(),
171
- frame_rate=sample_rate,
172
- sample_width=data.dtype.itemsize,
173
- channels=(1 if len(data.shape) == 1 else data.shape[1]),
174
- )
175
- file = audio.export(filename, format=format)
176
- file.close() # type: ignore
177
-
178
-
179
- def convert_to_16_bit_wav(data):
180
- # Based on: https://docs.scipy.org/doc/scipy/reference/generated/scipy.io.wavfile.write.html
181
- warning = "Trying to convert audio automatically from {} to 16-bit int format."
182
- if data.dtype in [np.float64, np.float32, np.float16]:
183
- warnings.warn(warning.format(data.dtype))
184
- data = data / np.abs(data).max()
185
- data = data * 32767
186
- data = data.astype(np.int16)
187
- elif data.dtype == np.int32:
188
- warnings.warn(warning.format(data.dtype))
189
- data = data / 65538
190
- data = data.astype(np.int16)
191
- elif data.dtype == np.int16:
192
- pass
193
- elif data.dtype == np.uint16:
194
- warnings.warn(warning.format(data.dtype))
195
- data = data - 32768
196
- data = data.astype(np.int16)
197
- elif data.dtype == np.uint8:
198
- warnings.warn(warning.format(data.dtype))
199
- data = data * 257 - 32768
200
- data = data.astype(np.int16)
201
- else:
202
- raise ValueError(
203
- "Audio data cannot be converted automatically from "
204
- f"{data.dtype} to 16-bit int format."
205
- )
206
- return data
207
-
208
-
209
- ##################
210
- # OUTPUT
211
- ##################
212
-
213
-
214
- def _convert(image, dtype, force_copy=False, uniform=False):
215
- """
216
- Adapted from: https://github.com/scikit-image/scikit-image/blob/main/skimage/util/dtype.py#L510-L531
217
-
218
- Convert an image to the requested data-type.
219
- Warnings are issued in case of precision loss, or when negative values
220
- are clipped during conversion to unsigned integer types (sign loss).
221
- Floating point values are expected to be normalized and will be clipped
222
- to the range [0.0, 1.0] or [-1.0, 1.0] when converting to unsigned or
223
- signed integers respectively.
224
- Numbers are not shifted to the negative side when converting from
225
- unsigned to signed integer types. Negative values will be clipped when
226
- converting to unsigned integers.
227
- Parameters
228
- ----------
229
- image : ndarray
230
- Input image.
231
- dtype : dtype
232
- Target data-type.
233
- force_copy : bool, optional
234
- Force a copy of the data, irrespective of its current dtype.
235
- uniform : bool, optional
236
- Uniformly quantize the floating point range to the integer range.
237
- By default (uniform=False) floating point values are scaled and
238
- rounded to the nearest integers, which minimizes back and forth
239
- conversion errors.
240
- .. versionchanged :: 0.15
241
- ``_convert`` no longer warns about possible precision or sign
242
- information loss. See discussions on these warnings at:
243
- https://github.com/scikit-image/scikit-image/issues/2602
244
- https://github.com/scikit-image/scikit-image/issues/543#issuecomment-208202228
245
- https://github.com/scikit-image/scikit-image/pull/3575
246
- References
247
- ----------
248
- .. [1] DirectX data conversion rules.
249
- https://msdn.microsoft.com/en-us/library/windows/desktop/dd607323%28v=vs.85%29.aspx
250
- .. [2] Data Conversions. In "OpenGL ES 2.0 Specification v2.0.25",
251
- pp 7-8. Khronos Group, 2010.
252
- .. [3] Proper treatment of pixels as integers. A.W. Paeth.
253
- In "Graphics Gems I", pp 249-256. Morgan Kaufmann, 1990.
254
- .. [4] Dirty Pixels. J. Blinn. In "Jim Blinn's corner: Dirty Pixels",
255
- pp 47-57. Morgan Kaufmann, 1998.
256
- """
257
- dtype_range = {
258
- bool: (False, True),
259
- np.bool_: (False, True),
260
- np.bool8: (False, True),
261
- float: (-1, 1),
262
- np.float_: (-1, 1),
263
- np.float16: (-1, 1),
264
- np.float32: (-1, 1),
265
- np.float64: (-1, 1),
266
- }
267
-
268
- def _dtype_itemsize(itemsize, *dtypes):
269
- """Return first of `dtypes` with itemsize greater than `itemsize`
270
- Parameters
271
- ----------
272
- itemsize: int
273
- The data type object element size.
274
- Other Parameters
275
- ----------------
276
- *dtypes:
277
- Any Object accepted by `np.dtype` to be converted to a data
278
- type object
279
- Returns
280
- -------
281
- dtype: data type object
282
- First of `dtypes` with itemsize greater than `itemsize`.
283
- """
284
- return next(dt for dt in dtypes if np.dtype(dt).itemsize >= itemsize)
285
-
286
- def _dtype_bits(kind, bits, itemsize=1):
287
- """Return dtype of `kind` that can store a `bits` wide unsigned int
288
- Parameters:
289
- kind: str
290
- Data type kind.
291
- bits: int
292
- Desired number of bits.
293
- itemsize: int
294
- The data type object element size.
295
- Returns
296
- -------
297
- dtype: data type object
298
- Data type of `kind` that can store a `bits` wide unsigned int
299
- """
300
-
301
- s = next(
302
- i
303
- for i in (itemsize,) + (2, 4, 8)
304
- if bits < (i * 8) or (bits == (i * 8) and kind == "u")
305
- )
306
-
307
- return np.dtype(kind + str(s))
308
-
309
- def _scale(a, n, m, copy=True):
310
- """Scale an array of unsigned/positive integers from `n` to `m` bits.
311
- Numbers can be represented exactly only if `m` is a multiple of `n`.
312
- Parameters
313
- ----------
314
- a : ndarray
315
- Input image array.
316
- n : int
317
- Number of bits currently used to encode the values in `a`.
318
- m : int
319
- Desired number of bits to encode the values in `out`.
320
- copy : bool, optional
321
- If True, allocates and returns new array. Otherwise, modifies
322
- `a` in place.
323
- Returns
324
- -------
325
- out : array
326
- Output image array. Has the same kind as `a`.
327
- """
328
- kind = a.dtype.kind
329
- if n > m and a.max() < 2**m:
330
- return a.astype(_dtype_bits(kind, m))
331
- elif n == m:
332
- return a.copy() if copy else a
333
- elif n > m:
334
- # downscale with precision loss
335
- if copy:
336
- b = np.empty(a.shape, _dtype_bits(kind, m))
337
- np.floor_divide(a, 2 ** (n - m), out=b, dtype=a.dtype, casting="unsafe")
338
- return b
339
- else:
340
- a //= 2 ** (n - m)
341
- return a
342
- elif m % n == 0:
343
- # exact upscale to a multiple of `n` bits
344
- if copy:
345
- b = np.empty(a.shape, _dtype_bits(kind, m))
346
- np.multiply(a, (2**m - 1) // (2**n - 1), out=b, dtype=b.dtype)
347
- return b
348
- else:
349
- a = a.astype(_dtype_bits(kind, m, a.dtype.itemsize), copy=False)
350
- a *= (2**m - 1) // (2**n - 1)
351
- return a
352
- else:
353
- # upscale to a multiple of `n` bits,
354
- # then downscale with precision loss
355
- o = (m // n + 1) * n
356
- if copy:
357
- b = np.empty(a.shape, _dtype_bits(kind, o))
358
- np.multiply(a, (2**o - 1) // (2**n - 1), out=b, dtype=b.dtype)
359
- b //= 2 ** (o - m)
360
- return b
361
- else:
362
- a = a.astype(_dtype_bits(kind, o, a.dtype.itemsize), copy=False)
363
- a *= (2**o - 1) // (2**n - 1)
364
- a //= 2 ** (o - m)
365
- return a
366
-
367
- image = np.asarray(image)
368
- dtypeobj_in = image.dtype
369
- dtypeobj_out = np.dtype("float64") if dtype is np.floating else np.dtype(dtype)
370
- dtype_in = dtypeobj_in.type
371
- dtype_out = dtypeobj_out.type
372
- kind_in = dtypeobj_in.kind
373
- kind_out = dtypeobj_out.kind
374
- itemsize_in = dtypeobj_in.itemsize
375
- itemsize_out = dtypeobj_out.itemsize
376
-
377
- # Below, we do an `issubdtype` check. Its purpose is to find out
378
- # whether we can get away without doing any image conversion. This happens
379
- # when:
380
- #
381
- # - the output and input dtypes are the same or
382
- # - when the output is specified as a type, and the input dtype
383
- # is a subclass of that type (e.g. `np.floating` will allow
384
- # `float32` and `float64` arrays through)
385
-
386
- if np.issubdtype(dtype_in, np.obj2sctype(dtype)):
387
- if force_copy:
388
- image = image.copy()
389
- return image
390
-
391
- if kind_in in "ui":
392
- imin_in = np.iinfo(dtype_in).min
393
- imax_in = np.iinfo(dtype_in).max
394
- if kind_out in "ui":
395
- imin_out = np.iinfo(dtype_out).min # type: ignore
396
- imax_out = np.iinfo(dtype_out).max # type: ignore
397
-
398
- # any -> binary
399
- if kind_out == "b":
400
- return image > dtype_in(dtype_range[dtype_in][1] / 2)
401
-
402
- # binary -> any
403
- if kind_in == "b":
404
- result = image.astype(dtype_out)
405
- if kind_out != "f":
406
- result *= dtype_out(dtype_range[dtype_out][1])
407
- return result
408
-
409
- # float -> any
410
- if kind_in == "f":
411
- if kind_out == "f":
412
- # float -> float
413
- return image.astype(dtype_out)
414
-
415
- if np.min(image) < -1.0 or np.max(image) > 1.0:
416
- raise ValueError("Images of type float must be between -1 and 1.")
417
- # floating point -> integer
418
- # use float type that can represent output integer type
419
- computation_type = _dtype_itemsize(
420
- itemsize_out, dtype_in, np.float32, np.float64
421
- )
422
-
423
- if not uniform:
424
- if kind_out == "u":
425
- image_out = np.multiply(image, imax_out, dtype=computation_type) # type: ignore
426
- else:
427
- image_out = np.multiply(
428
- image, (imax_out - imin_out) / 2, dtype=computation_type # type: ignore
429
- )
430
- image_out -= 1.0 / 2.0
431
- np.rint(image_out, out=image_out)
432
- np.clip(image_out, imin_out, imax_out, out=image_out) # type: ignore
433
- elif kind_out == "u":
434
- image_out = np.multiply(image, imax_out + 1, dtype=computation_type) # type: ignore
435
- np.clip(image_out, 0, imax_out, out=image_out) # type: ignore
436
- else:
437
- image_out = np.multiply(
438
- image, (imax_out - imin_out + 1.0) / 2.0, dtype=computation_type # type: ignore
439
- )
440
- np.floor(image_out, out=image_out)
441
- np.clip(image_out, imin_out, imax_out, out=image_out) # type: ignore
442
- return image_out.astype(dtype_out)
443
-
444
- # signed/unsigned int -> float
445
- if kind_out == "f":
446
- # use float type that can exactly represent input integers
447
- computation_type = _dtype_itemsize(
448
- itemsize_in, dtype_out, np.float32, np.float64
449
- )
450
-
451
- if kind_in == "u":
452
- # using np.divide or np.multiply doesn't copy the data
453
- # until the computation time
454
- image = np.multiply(image, 1.0 / imax_in, dtype=computation_type) # type: ignore
455
- # DirectX uses this conversion also for signed ints
456
- # if imin_in:
457
- # np.maximum(image, -1.0, out=image)
458
- else:
459
- image = np.add(image, 0.5, dtype=computation_type)
460
- image *= 2 / (imax_in - imin_in) # type: ignore
461
-
462
- return np.asarray(image, dtype_out)
463
-
464
- # unsigned int -> signed/unsigned int
465
- if kind_in == "u":
466
- if kind_out == "i":
467
- # unsigned int -> signed int
468
- image = _scale(image, 8 * itemsize_in, 8 * itemsize_out - 1)
469
- return image.view(dtype_out)
470
- else:
471
- # unsigned int -> unsigned int
472
- return _scale(image, 8 * itemsize_in, 8 * itemsize_out)
473
-
474
- # signed int -> unsigned int
475
- if kind_out == "u":
476
- image = _scale(image, 8 * itemsize_in - 1, 8 * itemsize_out)
477
- result = np.empty(image.shape, dtype_out)
478
- np.maximum(image, 0, out=result, dtype=image.dtype, casting="unsafe")
479
- return result
480
-
481
- # signed int -> signed int
482
- if itemsize_in > itemsize_out:
483
- return _scale(image, 8 * itemsize_in - 1, 8 * itemsize_out - 1)
484
-
485
- image = image.astype(_dtype_bits("i", itemsize_out * 8))
486
- image -= imin_in # type: ignore
487
- image = _scale(image, 8 * itemsize_in, 8 * itemsize_out, copy=False)
488
- image += imin_out # type: ignore
489
- return image.astype(dtype_out)
490
-
491
-
492
- def ffmpeg_installed() -> bool:
493
- if wasm_utils.IS_WASM:
494
- # TODO: Support ffmpeg in WASM
495
- return False
496
-
497
- return shutil.which("ffmpeg") is not None
498
-
499
-
500
- def video_is_playable(video_filepath: str) -> bool:
501
- """Determines if a video is playable in the browser.
502
-
503
- A video is playable if it has a playable container and codec.
504
- .mp4 -> h264
505
- .webm -> vp9
506
- .ogg -> theora
507
- """
508
- try:
509
- container = Path(video_filepath).suffix.lower()
510
- probe = FFprobe(
511
- global_options="-show_format -show_streams -select_streams v -print_format json",
512
- inputs={video_filepath: None},
513
- )
514
- output = probe.run(stderr=subprocess.PIPE, stdout=subprocess.PIPE)
515
- output = json.loads(output[0])
516
- video_codec = output["streams"][0]["codec_name"]
517
- return (container, video_codec) in [
518
- (".mp4", "h264"),
519
- (".ogg", "theora"),
520
- (".webm", "vp9"),
521
- ]
522
- # If anything goes wrong, assume the video can be played to not convert downstream
523
- except (FFRuntimeError, IndexError, KeyError):
524
- return True
525
-
526
-
527
- def convert_video_to_playable_mp4(video_path: str) -> str:
528
- """Convert the video to mp4. If something goes wrong return the original video."""
529
- try:
530
- with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
531
- output_path = Path(video_path).with_suffix(".mp4")
532
- shutil.copy2(video_path, tmp_file.name)
533
- # ffmpeg will automatically use h264 codec (playable in browser) when converting to mp4
534
- ff = FFmpeg(
535
- inputs={str(tmp_file.name): None},
536
- outputs={str(output_path): None},
537
- global_options="-y -loglevel quiet",
538
- )
539
- ff.run()
540
- except FFRuntimeError as e:
541
- print(f"Error converting video to browser-playable format {str(e)}")
542
- output_path = video_path
543
- finally:
544
- # Remove temp file
545
- os.remove(tmp_file.name) # type: ignore
546
- return str(output_path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/huggingface_hub/_commit_api.py DELETED
@@ -1,632 +0,0 @@
1
- """
2
- Type definitions and utilities for the `create_commit` API
3
- """
4
- import base64
5
- import io
6
- import os
7
- import warnings
8
- from collections import defaultdict
9
- from contextlib import contextmanager
10
- from dataclasses import dataclass, field
11
- from itertools import groupby
12
- from pathlib import Path, PurePosixPath
13
- from typing import TYPE_CHECKING, Any, BinaryIO, Dict, Iterable, Iterator, List, Optional, Tuple, Union
14
-
15
- from tqdm.contrib.concurrent import thread_map
16
-
17
- from huggingface_hub import get_session
18
-
19
- from .constants import ENDPOINT, HF_HUB_ENABLE_HF_TRANSFER
20
- from .lfs import UploadInfo, lfs_upload, post_lfs_batch_info
21
- from .utils import (
22
- EntryNotFoundError,
23
- build_hf_headers,
24
- chunk_iterable,
25
- hf_raise_for_status,
26
- logging,
27
- tqdm_stream_file,
28
- validate_hf_hub_args,
29
- )
30
- from .utils import tqdm as hf_tqdm
31
- from .utils._typing import Literal
32
-
33
-
34
- if TYPE_CHECKING:
35
- from .hf_api import RepoFile
36
-
37
-
38
- logger = logging.get_logger(__name__)
39
-
40
-
41
- UploadMode = Literal["lfs", "regular"]
42
-
43
- # Max is 1,000 per request on the Hub for HfApi.list_files_info
44
- # Otherwise we get:
45
- # HfHubHTTPError: 413 Client Error: Payload Too Large for url: https://huggingface.co/api/datasets/xxx (Request ID: xxx)\n\ntoo many parameters
46
- # See https://github.com/huggingface/huggingface_hub/issues/1503
47
- FETCH_LFS_BATCH_SIZE = 500
48
-
49
-
50
- @dataclass
51
- class CommitOperationDelete:
52
- """
53
- Data structure holding necessary info to delete a file or a folder from a repository
54
- on the Hub.
55
-
56
- Args:
57
- path_in_repo (`str`):
58
- Relative filepath in the repo, for example: `"checkpoints/1fec34a/weights.bin"`
59
- for a file or `"checkpoints/1fec34a/"` for a folder.
60
- is_folder (`bool` or `Literal["auto"]`, *optional*)
61
- Whether the Delete Operation applies to a folder or not. If "auto", the path
62
- type (file or folder) is guessed automatically by looking if path ends with
63
- a "/" (folder) or not (file). To explicitly set the path type, you can set
64
- `is_folder=True` or `is_folder=False`.
65
- """
66
-
67
- path_in_repo: str
68
- is_folder: Union[bool, Literal["auto"]] = "auto"
69
-
70
- def __post_init__(self):
71
- self.path_in_repo = _validate_path_in_repo(self.path_in_repo)
72
-
73
- if self.is_folder == "auto":
74
- self.is_folder = self.path_in_repo.endswith("/")
75
- if not isinstance(self.is_folder, bool):
76
- raise ValueError(
77
- f"Wrong value for `is_folder`. Must be one of [`True`, `False`, `'auto'`]. Got '{self.is_folder}'."
78
- )
79
-
80
-
81
- @dataclass
82
- class CommitOperationCopy:
83
- """
84
- Data structure holding necessary info to copy a file in a repository on the Hub.
85
-
86
- Limitations:
87
- - Only LFS files can be copied. To copy a regular file, you need to download it locally and re-upload it
88
- - Cross-repository copies are not supported.
89
-
90
- Note: you can combine a [`CommitOperationCopy`] and a [`CommitOperationDelete`] to rename an LFS file on the Hub.
91
-
92
- Args:
93
- src_path_in_repo (`str`):
94
- Relative filepath in the repo of the file to be copied, e.g. `"checkpoints/1fec34a/weights.bin"`.
95
- path_in_repo (`str`):
96
- Relative filepath in the repo where to copy the file, e.g. `"checkpoints/1fec34a/weights_copy.bin"`.
97
- src_revision (`str`, *optional*):
98
- The git revision of the file to be copied. Can be any valid git revision.
99
- Default to the target commit revision.
100
- """
101
-
102
- src_path_in_repo: str
103
- path_in_repo: str
104
- src_revision: Optional[str] = None
105
-
106
- def __post_init__(self):
107
- self.src_path_in_repo = _validate_path_in_repo(self.src_path_in_repo)
108
- self.path_in_repo = _validate_path_in_repo(self.path_in_repo)
109
-
110
-
111
- @dataclass
112
- class CommitOperationAdd:
113
- """
114
- Data structure holding necessary info to upload a file to a repository on the Hub.
115
-
116
- Args:
117
- path_in_repo (`str`):
118
- Relative filepath in the repo, for example: `"checkpoints/1fec34a/weights.bin"`
119
- path_or_fileobj (`str`, `Path`, `bytes`, or `BinaryIO`):
120
- Either:
121
- - a path to a local file (as `str` or `pathlib.Path`) to upload
122
- - a buffer of bytes (`bytes`) holding the content of the file to upload
123
- - a "file object" (subclass of `io.BufferedIOBase`), typically obtained
124
- with `open(path, "rb")`. It must support `seek()` and `tell()` methods.
125
-
126
- Raises:
127
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
128
- If `path_or_fileobj` is not one of `str`, `Path`, `bytes` or `io.BufferedIOBase`.
129
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
130
- If `path_or_fileobj` is a `str` or `Path` but not a path to an existing file.
131
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
132
- If `path_or_fileobj` is a `io.BufferedIOBase` but it doesn't support both
133
- `seek()` and `tell()`.
134
- """
135
-
136
- path_in_repo: str
137
- path_or_fileobj: Union[str, Path, bytes, BinaryIO]
138
- upload_info: UploadInfo = field(init=False, repr=False)
139
-
140
- def __post_init__(self) -> None:
141
- """Validates `path_or_fileobj` and compute `upload_info`."""
142
- self.path_in_repo = _validate_path_in_repo(self.path_in_repo)
143
-
144
- # Validate `path_or_fileobj` value
145
- if isinstance(self.path_or_fileobj, Path):
146
- self.path_or_fileobj = str(self.path_or_fileobj)
147
- if isinstance(self.path_or_fileobj, str):
148
- path_or_fileobj = os.path.normpath(os.path.expanduser(self.path_or_fileobj))
149
- if not os.path.isfile(path_or_fileobj):
150
- raise ValueError(f"Provided path: '{path_or_fileobj}' is not a file on the local file system")
151
- elif not isinstance(self.path_or_fileobj, (io.BufferedIOBase, bytes)):
152
- # ^^ Inspired from: https://stackoverflow.com/questions/44584829/how-to-determine-if-file-is-opened-in-binary-or-text-mode
153
- raise ValueError(
154
- "path_or_fileobj must be either an instance of str, bytes or"
155
- " io.BufferedIOBase. If you passed a file-like object, make sure it is"
156
- " in binary mode."
157
- )
158
- if isinstance(self.path_or_fileobj, io.BufferedIOBase):
159
- try:
160
- self.path_or_fileobj.tell()
161
- self.path_or_fileobj.seek(0, os.SEEK_CUR)
162
- except (OSError, AttributeError) as exc:
163
- raise ValueError(
164
- "path_or_fileobj is a file-like object but does not implement seek() and tell()"
165
- ) from exc
166
-
167
- # Compute "upload_info" attribute
168
- if isinstance(self.path_or_fileobj, str):
169
- self.upload_info = UploadInfo.from_path(self.path_or_fileobj)
170
- elif isinstance(self.path_or_fileobj, bytes):
171
- self.upload_info = UploadInfo.from_bytes(self.path_or_fileobj)
172
- else:
173
- self.upload_info = UploadInfo.from_fileobj(self.path_or_fileobj)
174
-
175
- @contextmanager
176
- def as_file(self, with_tqdm: bool = False) -> Iterator[BinaryIO]:
177
- """
178
- A context manager that yields a file-like object allowing to read the underlying
179
- data behind `path_or_fileobj`.
180
-
181
- Args:
182
- with_tqdm (`bool`, *optional*, defaults to `False`):
183
- If True, iterating over the file object will display a progress bar. Only
184
- works if the file-like object is a path to a file. Pure bytes and buffers
185
- are not supported.
186
-
187
- Example:
188
-
189
- ```python
190
- >>> operation = CommitOperationAdd(
191
- ... path_in_repo="remote/dir/weights.h5",
192
- ... path_or_fileobj="./local/weights.h5",
193
- ... )
194
- CommitOperationAdd(path_in_repo='remote/dir/weights.h5', path_or_fileobj='./local/weights.h5')
195
-
196
- >>> with operation.as_file() as file:
197
- ... content = file.read()
198
-
199
- >>> with operation.as_file(with_tqdm=True) as file:
200
- ... while True:
201
- ... data = file.read(1024)
202
- ... if not data:
203
- ... break
204
- config.json: 100%|█████████████████████████| 8.19k/8.19k [00:02<00:00, 3.72kB/s]
205
-
206
- >>> with operation.as_file(with_tqdm=True) as file:
207
- ... requests.put(..., data=file)
208
- config.json: 100%|█████████████████████████| 8.19k/8.19k [00:02<00:00, 3.72kB/s]
209
- ```
210
- """
211
- if isinstance(self.path_or_fileobj, str) or isinstance(self.path_or_fileobj, Path):
212
- if with_tqdm:
213
- with tqdm_stream_file(self.path_or_fileobj) as file:
214
- yield file
215
- else:
216
- with open(self.path_or_fileobj, "rb") as file:
217
- yield file
218
- elif isinstance(self.path_or_fileobj, bytes):
219
- yield io.BytesIO(self.path_or_fileobj)
220
- elif isinstance(self.path_or_fileobj, io.BufferedIOBase):
221
- prev_pos = self.path_or_fileobj.tell()
222
- yield self.path_or_fileobj
223
- self.path_or_fileobj.seek(prev_pos, io.SEEK_SET)
224
-
225
- def b64content(self) -> bytes:
226
- """
227
- The base64-encoded content of `path_or_fileobj`
228
-
229
- Returns: `bytes`
230
- """
231
- with self.as_file() as file:
232
- return base64.b64encode(file.read())
233
-
234
-
235
- def _validate_path_in_repo(path_in_repo: str) -> str:
236
- # Validate `path_in_repo` value to prevent a server-side issue
237
- if path_in_repo.startswith("/"):
238
- path_in_repo = path_in_repo[1:]
239
- if path_in_repo == "." or path_in_repo == ".." or path_in_repo.startswith("../"):
240
- raise ValueError(f"Invalid `path_in_repo` in CommitOperation: '{path_in_repo}'")
241
- if path_in_repo.startswith("./"):
242
- path_in_repo = path_in_repo[2:]
243
- if any(part == ".git" for part in path_in_repo.split("/")):
244
- raise ValueError(
245
- "Invalid `path_in_repo` in CommitOperation: cannot update files under a '.git/' folder (path:"
246
- f" '{path_in_repo}')."
247
- )
248
- return path_in_repo
249
-
250
-
251
- CommitOperation = Union[CommitOperationAdd, CommitOperationCopy, CommitOperationDelete]
252
-
253
-
254
- def warn_on_overwriting_operations(operations: List[CommitOperation]) -> None:
255
- """
256
- Warn user when a list of operations is expected to overwrite itself in a single
257
- commit.
258
-
259
- Rules:
260
- - If a filepath is updated by multiple `CommitOperationAdd` operations, a warning
261
- message is triggered.
262
- - If a filepath is updated at least once by a `CommitOperationAdd` and then deleted
263
- by a `CommitOperationDelete`, a warning is triggered.
264
- - If a `CommitOperationDelete` deletes a filepath that is then updated by a
265
- `CommitOperationAdd`, no warning is triggered. This is usually useless (no need to
266
- delete before upload) but can happen if a user deletes an entire folder and then
267
- add new files to it.
268
- """
269
- nb_additions_per_path: Dict[str, int] = defaultdict(int)
270
- for operation in operations:
271
- path_in_repo = operation.path_in_repo
272
- if isinstance(operation, CommitOperationAdd):
273
- if nb_additions_per_path[path_in_repo] > 0:
274
- warnings.warn(
275
- "About to update multiple times the same file in the same commit:"
276
- f" '{path_in_repo}'. This can cause undesired inconsistencies in"
277
- " your repo."
278
- )
279
- nb_additions_per_path[path_in_repo] += 1
280
- for parent in PurePosixPath(path_in_repo).parents:
281
- # Also keep track of number of updated files per folder
282
- # => warns if deleting a folder overwrite some contained files
283
- nb_additions_per_path[str(parent)] += 1
284
- if isinstance(operation, CommitOperationDelete):
285
- if nb_additions_per_path[str(PurePosixPath(path_in_repo))] > 0:
286
- if operation.is_folder:
287
- warnings.warn(
288
- "About to delete a folder containing files that have just been"
289
- f" updated within the same commit: '{path_in_repo}'. This can"
290
- " cause undesired inconsistencies in your repo."
291
- )
292
- else:
293
- warnings.warn(
294
- "About to delete a file that have just been updated within the"
295
- f" same commit: '{path_in_repo}'. This can cause undesired"
296
- " inconsistencies in your repo."
297
- )
298
-
299
-
300
- @validate_hf_hub_args
301
- def upload_lfs_files(
302
- *,
303
- additions: List[CommitOperationAdd],
304
- repo_type: str,
305
- repo_id: str,
306
- token: Optional[str],
307
- endpoint: Optional[str] = None,
308
- num_threads: int = 5,
309
- ):
310
- """
311
- Uploads the content of `additions` to the Hub using the large file storage protocol.
312
-
313
- Relevant external documentation:
314
- - LFS Batch API: https://github.com/git-lfs/git-lfs/blob/main/docs/api/batch.md
315
-
316
- Args:
317
- additions (`List` of `CommitOperationAdd`):
318
- The files to be uploaded
319
- repo_type (`str`):
320
- Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`.
321
- repo_id (`str`):
322
- A namespace (user or an organization) and a repo name separated
323
- by a `/`.
324
- token (`str`, *optional*):
325
- An authentication token ( See https://huggingface.co/settings/tokens )
326
- num_threads (`int`, *optional*):
327
- The number of concurrent threads to use when uploading. Defaults to 5.
328
-
329
-
330
- Raises: `RuntimeError` if an upload failed for any reason
331
-
332
- Raises: `ValueError` if the server returns malformed responses
333
-
334
- Raises: `requests.HTTPError` if the LFS batch endpoint returned an HTTP
335
- error
336
-
337
- """
338
- # Step 1: retrieve upload instructions from the LFS batch endpoint.
339
- # Upload instructions are retrieved by chunk of 256 files to avoid reaching
340
- # the payload limit.
341
- batch_actions: List[Dict] = []
342
- for chunk in chunk_iterable(additions, chunk_size=256):
343
- batch_actions_chunk, batch_errors_chunk = post_lfs_batch_info(
344
- upload_infos=[op.upload_info for op in chunk],
345
- token=token,
346
- repo_id=repo_id,
347
- repo_type=repo_type,
348
- endpoint=endpoint,
349
- )
350
-
351
- # If at least 1 error, we do not retrieve information for other chunks
352
- if batch_errors_chunk:
353
- message = "\n".join(
354
- [
355
- f'Encountered error for file with OID {err.get("oid")}: `{err.get("error", {}).get("message")}'
356
- for err in batch_errors_chunk
357
- ]
358
- )
359
- raise ValueError(f"LFS batch endpoint returned errors:\n{message}")
360
-
361
- batch_actions += batch_actions_chunk
362
- oid2addop = {add_op.upload_info.sha256.hex(): add_op for add_op in additions}
363
-
364
- # Step 2: ignore files that have already been uploaded
365
- filtered_actions = []
366
- for action in batch_actions:
367
- if action.get("actions") is None:
368
- logger.debug(
369
- f"Content of file {oid2addop[action['oid']].path_in_repo} is already"
370
- " present upstream - skipping upload."
371
- )
372
- else:
373
- filtered_actions.append(action)
374
-
375
- if len(filtered_actions) == 0:
376
- logger.debug("No LFS files to upload.")
377
- return
378
-
379
- # Step 3: upload files concurrently according to these instructions
380
- def _wrapped_lfs_upload(batch_action) -> None:
381
- try:
382
- operation = oid2addop[batch_action["oid"]]
383
- lfs_upload(operation=operation, lfs_batch_action=batch_action, token=token)
384
- except Exception as exc:
385
- raise RuntimeError(f"Error while uploading '{operation.path_in_repo}' to the Hub.") from exc
386
-
387
- if HF_HUB_ENABLE_HF_TRANSFER:
388
- logger.debug(f"Uploading {len(filtered_actions)} LFS files to the Hub using `hf_transfer`.")
389
- for action in hf_tqdm(filtered_actions):
390
- _wrapped_lfs_upload(action)
391
- elif len(filtered_actions) == 1:
392
- logger.debug("Uploading 1 LFS file to the Hub")
393
- _wrapped_lfs_upload(filtered_actions[0])
394
- else:
395
- logger.debug(
396
- f"Uploading {len(filtered_actions)} LFS files to the Hub using up to {num_threads} threads concurrently"
397
- )
398
- thread_map(
399
- _wrapped_lfs_upload,
400
- filtered_actions,
401
- desc=f"Upload {len(filtered_actions)} LFS files",
402
- max_workers=num_threads,
403
- tqdm_class=hf_tqdm,
404
- )
405
-
406
-
407
- def _validate_preupload_info(preupload_info: dict):
408
- files = preupload_info.get("files")
409
- if not isinstance(files, list):
410
- raise ValueError("preupload_info is improperly formatted")
411
- for file_info in files:
412
- if not (
413
- isinstance(file_info, dict)
414
- and isinstance(file_info.get("path"), str)
415
- and isinstance(file_info.get("uploadMode"), str)
416
- and (file_info["uploadMode"] in ("lfs", "regular"))
417
- ):
418
- raise ValueError("preupload_info is improperly formatted:")
419
- return preupload_info
420
-
421
-
422
- @validate_hf_hub_args
423
- def fetch_upload_modes(
424
- additions: Iterable[CommitOperationAdd],
425
- repo_type: str,
426
- repo_id: str,
427
- token: Optional[str],
428
- revision: str,
429
- endpoint: Optional[str] = None,
430
- create_pr: bool = False,
431
- ) -> Dict[str, UploadMode]:
432
- """
433
- Requests the Hub "preupload" endpoint to determine whether each input file
434
- should be uploaded as a regular git blob or as git LFS blob.
435
-
436
- Args:
437
- additions (`Iterable` of :class:`CommitOperationAdd`):
438
- Iterable of :class:`CommitOperationAdd` describing the files to
439
- upload to the Hub.
440
- repo_type (`str`):
441
- Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`.
442
- repo_id (`str`):
443
- A namespace (user or an organization) and a repo name separated
444
- by a `/`.
445
- token (`str`, *optional*):
446
- An authentication token ( See https://huggingface.co/settings/tokens )
447
- revision (`str`):
448
- The git revision to upload the files to. Can be any valid git revision.
449
-
450
- Returns: `Dict[str, UploadMode]`
451
- Key is the file path, value is the upload mode ("regular" or "lfs").
452
-
453
- Raises:
454
- [`~utils.HfHubHTTPError`]
455
- If the Hub API returned an error.
456
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
457
- If the Hub API response is improperly formatted.
458
- """
459
- endpoint = endpoint if endpoint is not None else ENDPOINT
460
- headers = build_hf_headers(token=token)
461
-
462
- # Fetch upload mode (LFS or regular) chunk by chunk.
463
- upload_modes: Dict[str, UploadMode] = {}
464
- for chunk in chunk_iterable(additions, 256):
465
- payload = {
466
- "files": [
467
- {
468
- "path": op.path_in_repo,
469
- "sample": base64.b64encode(op.upload_info.sample).decode("ascii"),
470
- "size": op.upload_info.size,
471
- "sha": op.upload_info.sha256.hex(),
472
- }
473
- for op in chunk
474
- ]
475
- }
476
-
477
- resp = get_session().post(
478
- f"{endpoint}/api/{repo_type}s/{repo_id}/preupload/{revision}",
479
- json=payload,
480
- headers=headers,
481
- params={"create_pr": "1"} if create_pr else None,
482
- )
483
- hf_raise_for_status(resp)
484
- preupload_info = _validate_preupload_info(resp.json())
485
- upload_modes.update(**{file["path"]: file["uploadMode"] for file in preupload_info["files"]})
486
-
487
- # Empty files cannot be uploaded as LFS (S3 would fail with a 501 Not Implemented)
488
- # => empty files are uploaded as "regular" to still allow users to commit them.
489
- for addition in additions:
490
- if addition.upload_info.size == 0:
491
- path = addition.path_in_repo
492
- upload_modes[path] = "regular"
493
-
494
- return upload_modes
495
-
496
-
497
- @validate_hf_hub_args
498
- def fetch_lfs_files_to_copy(
499
- copies: Iterable[CommitOperationCopy],
500
- repo_type: str,
501
- repo_id: str,
502
- token: Optional[str],
503
- revision: str,
504
- endpoint: Optional[str] = None,
505
- ) -> Dict[Tuple[str, Optional[str]], "RepoFile"]:
506
- """
507
- Requests the Hub files information of the LFS files to be copied, including their sha256.
508
-
509
- Args:
510
- copies (`Iterable` of :class:`CommitOperationCopy`):
511
- Iterable of :class:`CommitOperationCopy` describing the files to
512
- copy on the Hub.
513
- repo_type (`str`):
514
- Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`.
515
- repo_id (`str`):
516
- A namespace (user or an organization) and a repo name separated
517
- by a `/`.
518
- token (`str`, *optional*):
519
- An authentication token ( See https://huggingface.co/settings/tokens )
520
- revision (`str`):
521
- The git revision to upload the files to. Can be any valid git revision.
522
-
523
- Returns: `Dict[Tuple[str, Optional[str]], RepoFile]]`
524
- Key is the file path and revision of the file to copy, value is the repo file.
525
-
526
- Raises:
527
- [`~utils.HfHubHTTPError`]
528
- If the Hub API returned an error.
529
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
530
- If the Hub API response is improperly formatted.
531
- """
532
- from .hf_api import HfApi
533
-
534
- hf_api = HfApi(endpoint=endpoint, token=token)
535
- files_to_copy = {}
536
- for src_revision, operations in groupby(copies, key=lambda op: op.src_revision):
537
- operations = list(operations) # type: ignore
538
- paths = [op.src_path_in_repo for op in operations]
539
- for offset in range(0, len(paths), FETCH_LFS_BATCH_SIZE):
540
- src_repo_files = hf_api.list_files_info(
541
- repo_id=repo_id,
542
- paths=paths[offset : offset + FETCH_LFS_BATCH_SIZE],
543
- revision=src_revision or revision,
544
- repo_type=repo_type,
545
- )
546
- for src_repo_file in src_repo_files:
547
- if not src_repo_file.lfs:
548
- raise NotImplementedError("Copying a non-LFS file is not implemented")
549
- files_to_copy[(src_repo_file.rfilename, src_revision)] = src_repo_file
550
- for operation in operations:
551
- if (operation.src_path_in_repo, src_revision) not in files_to_copy:
552
- raise EntryNotFoundError(
553
- f"Cannot copy {operation.src_path_in_repo} at revision "
554
- f"{src_revision or revision}: file is missing on repo."
555
- )
556
- return files_to_copy
557
-
558
-
559
- def prepare_commit_payload(
560
- operations: Iterable[CommitOperation],
561
- upload_modes: Dict[str, UploadMode],
562
- files_to_copy: Dict[Tuple[str, Optional[str]], "RepoFile"],
563
- commit_message: str,
564
- commit_description: Optional[str] = None,
565
- parent_commit: Optional[str] = None,
566
- ) -> Iterable[Dict[str, Any]]:
567
- """
568
- Builds the payload to POST to the `/commit` API of the Hub.
569
-
570
- Payload is returned as an iterator so that it can be streamed as a ndjson in the
571
- POST request.
572
-
573
- For more information, see:
574
- - https://github.com/huggingface/huggingface_hub/issues/1085#issuecomment-1265208073
575
- - http://ndjson.org/
576
- """
577
- commit_description = commit_description if commit_description is not None else ""
578
-
579
- # 1. Send a header item with the commit metadata
580
- header_value = {"summary": commit_message, "description": commit_description}
581
- if parent_commit is not None:
582
- header_value["parentCommit"] = parent_commit
583
- yield {"key": "header", "value": header_value}
584
-
585
- # 2. Send operations, one per line
586
- for operation in operations:
587
- # 2.a. Case adding a regular file
588
- if isinstance(operation, CommitOperationAdd) and upload_modes.get(operation.path_in_repo) == "regular":
589
- yield {
590
- "key": "file",
591
- "value": {
592
- "content": operation.b64content().decode(),
593
- "path": operation.path_in_repo,
594
- "encoding": "base64",
595
- },
596
- }
597
- # 2.b. Case adding an LFS file
598
- elif isinstance(operation, CommitOperationAdd) and upload_modes.get(operation.path_in_repo) == "lfs":
599
- yield {
600
- "key": "lfsFile",
601
- "value": {
602
- "path": operation.path_in_repo,
603
- "algo": "sha256",
604
- "oid": operation.upload_info.sha256.hex(),
605
- "size": operation.upload_info.size,
606
- },
607
- }
608
- # 2.c. Case deleting a file or folder
609
- elif isinstance(operation, CommitOperationDelete):
610
- yield {
611
- "key": "deletedFolder" if operation.is_folder else "deletedFile",
612
- "value": {"path": operation.path_in_repo},
613
- }
614
- # 2.d. Case copying a file or folder
615
- elif isinstance(operation, CommitOperationCopy):
616
- file_to_copy = files_to_copy[(operation.src_path_in_repo, operation.src_revision)]
617
- if not file_to_copy.lfs:
618
- raise NotImplementedError("Copying a non-LFS file is not implemented")
619
- yield {
620
- "key": "lfsFile",
621
- "value": {
622
- "path": operation.path_in_repo,
623
- "algo": "sha256",
624
- "oid": file_to_copy.lfs["sha256"],
625
- },
626
- }
627
- # 2.e. Never expected to happen
628
- else:
629
- raise ValueError(
630
- f"Unknown operation to commit. Operation: {operation}. Upload mode:"
631
- f" {upload_modes.get(operation.path_in_repo)}"
632
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Daniil-plotnikov/Daniil-plotnikov-russian-vision-v4/app.py DELETED
@@ -1,3 +0,0 @@
1
- import gradio as gr
2
-
3
- gr.Interface.load("models/Daniil-plotnikov/russian-vision-v4").launch()
 
 
 
 
spaces/Datasculptor/LoRA-DreamBooth-Training-UI/trainer.py DELETED
@@ -1,166 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import datetime
4
- import os
5
- import pathlib
6
- import shlex
7
- import shutil
8
- import subprocess
9
-
10
- import gradio as gr
11
- import PIL.Image
12
- import slugify
13
- import torch
14
- from huggingface_hub import HfApi
15
-
16
- from app_upload import LoRAModelUploader
17
- from utils import save_model_card
18
-
19
- URL_TO_JOIN_LORA_LIBRARY_ORG = 'https://huggingface.co/organizations/lora-library/share/hjetHAcKjnPHXhHfbeEcqnBqmhgilFfpOL'
20
-
21
-
22
- def pad_image(image: PIL.Image.Image) -> PIL.Image.Image:
23
- w, h = image.size
24
- if w == h:
25
- return image
26
- elif w > h:
27
- new_image = PIL.Image.new(image.mode, (w, w), (0, 0, 0))
28
- new_image.paste(image, (0, (w - h) // 2))
29
- return new_image
30
- else:
31
- new_image = PIL.Image.new(image.mode, (h, h), (0, 0, 0))
32
- new_image.paste(image, ((h - w) // 2, 0))
33
- return new_image
34
-
35
-
36
- class Trainer:
37
- def __init__(self, hf_token: str | None = None):
38
- self.hf_token = hf_token
39
- self.api = HfApi(token=hf_token)
40
- self.model_uploader = LoRAModelUploader(hf_token)
41
-
42
- def prepare_dataset(self, instance_images: list, resolution: int,
43
- instance_data_dir: pathlib.Path) -> None:
44
- shutil.rmtree(instance_data_dir, ignore_errors=True)
45
- instance_data_dir.mkdir(parents=True)
46
- for i, temp_path in enumerate(instance_images):
47
- image = PIL.Image.open(temp_path.name)
48
- image = pad_image(image)
49
- image = image.resize((resolution, resolution))
50
- image = image.convert('RGB')
51
- out_path = instance_data_dir / f'{i:03d}.jpg'
52
- image.save(out_path, format='JPEG', quality=100)
53
-
54
- def join_lora_library_org(self) -> None:
55
- subprocess.run(
56
- shlex.split(
57
- f'curl -X POST -H "Authorization: Bearer {self.hf_token}" -H "Content-Type: application/json" {URL_TO_JOIN_LORA_LIBRARY_ORG}'
58
- ))
59
-
60
- def run(
61
- self,
62
- instance_images: list | None,
63
- instance_prompt: str,
64
- output_model_name: str,
65
- overwrite_existing_model: bool,
66
- validation_prompt: str,
67
- base_model: str,
68
- resolution_s: str,
69
- n_steps: int,
70
- learning_rate: float,
71
- gradient_accumulation: int,
72
- seed: int,
73
- fp16: bool,
74
- use_8bit_adam: bool,
75
- checkpointing_steps: int,
76
- use_wandb: bool,
77
- validation_epochs: int,
78
- upload_to_hub: bool,
79
- use_private_repo: bool,
80
- delete_existing_repo: bool,
81
- upload_to: str,
82
- remove_gpu_after_training: bool,
83
- ) -> str:
84
- if not torch.cuda.is_available():
85
- raise gr.Error('CUDA is not available.')
86
- if instance_images is None:
87
- raise gr.Error('You need to upload images.')
88
- if not instance_prompt:
89
- raise gr.Error('The instance prompt is missing.')
90
- if not validation_prompt:
91
- raise gr.Error('The validation prompt is missing.')
92
-
93
- resolution = int(resolution_s)
94
-
95
- if not output_model_name:
96
- timestamp = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
97
- output_model_name = f'lora-dreambooth-{timestamp}'
98
- output_model_name = slugify.slugify(output_model_name)
99
-
100
- repo_dir = pathlib.Path(__file__).parent
101
- output_dir = repo_dir / 'experiments' / output_model_name
102
- if overwrite_existing_model or upload_to_hub:
103
- shutil.rmtree(output_dir, ignore_errors=True)
104
- output_dir.mkdir(parents=True)
105
-
106
- instance_data_dir = repo_dir / 'training_data' / output_model_name
107
- self.prepare_dataset(instance_images, resolution, instance_data_dir)
108
-
109
- if upload_to_hub:
110
- self.join_lora_library_org()
111
-
112
- command = f'''
113
- accelerate launch train_dreambooth_lora.py \
114
- --pretrained_model_name_or_path={base_model} \
115
- --instance_data_dir={instance_data_dir} \
116
- --output_dir={output_dir} \
117
- --instance_prompt="{instance_prompt}" \
118
- --resolution={resolution} \
119
- --train_batch_size=1 \
120
- --gradient_accumulation_steps={gradient_accumulation} \
121
- --learning_rate={learning_rate} \
122
- --lr_scheduler=constant \
123
- --lr_warmup_steps=0 \
124
- --max_train_steps={n_steps} \
125
- --checkpointing_steps={checkpointing_steps} \
126
- --validation_prompt="{validation_prompt}" \
127
- --validation_epochs={validation_epochs} \
128
- --seed={seed}
129
- '''
130
- if fp16:
131
- command += ' --mixed_precision fp16'
132
- if use_8bit_adam:
133
- command += ' --use_8bit_adam'
134
- if use_wandb:
135
- command += ' --report_to wandb'
136
-
137
- with open(output_dir / 'train.sh', 'w') as f:
138
- command_s = ' '.join(command.split())
139
- f.write(command_s)
140
- subprocess.run(shlex.split(command))
141
- save_model_card(save_dir=output_dir,
142
- base_model=base_model,
143
- instance_prompt=instance_prompt,
144
- test_prompt=validation_prompt,
145
- test_image_dir='test_images')
146
-
147
- message = 'Training completed!'
148
- print(message)
149
-
150
- if upload_to_hub:
151
- upload_message = self.model_uploader.upload_lora_model(
152
- folder_path=output_dir.as_posix(),
153
- repo_name=output_model_name,
154
- upload_to=upload_to,
155
- private=use_private_repo,
156
- delete_existing_repo=delete_existing_repo)
157
- print(upload_message)
158
- message = message + '\n' + upload_message
159
-
160
- if remove_gpu_after_training:
161
- space_id = os.getenv('SPACE_ID')
162
- if space_id:
163
- self.api.request_space_hardware(repo_id=space_id,
164
- hardware='cpu-basic')
165
-
166
- return message