NeoPy commited on
Commit
21fa86b
Β·
verified Β·
1 Parent(s): 8ceb8fc

Upload folder using huggingface_hub

Browse files
Files changed (2) hide show
  1. app.py +177 -172
  2. requirements.txt +9 -6
app.py CHANGED
@@ -1,181 +1,186 @@
1
- import subprocess
2
- import os
3
  import gradio as gr
4
- import torch
5
- import numpy as np
6
- from PIL import Image, ImageEnhance
7
  from pathlib import Path
 
8
 
9
- # Constants
10
- DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
11
- MAX_SEED = np.iinfo(np.int32).max
12
  OUTPUT_DIR = Path("output_minecraft_skins")
13
-
14
- print(f"Using: {DEVICE}")
15
-
16
- # Repo URL
17
- REPO_URL = "https://github.com/BF667/Minecraft_Skin_Generator.git"
18
- REPO_NAME = "Minecraft_Skin_Generator"
19
- REPO_PATH = Path(REPO_NAME)
20
-
21
- def setup_repository():
22
- """Clones or updates the Git repository."""
23
- if not REPO_PATH.exists():
24
- print(f"Cloning {REPO_NAME} repository...")
25
- try:
26
- subprocess.run(["git", "clone", REPO_URL], check=True)
27
- print("Repository cloned successfully.")
28
- except subprocess.CalledProcessError as e:
29
- print(f"Error cloning repository: {e}")
30
- raise
31
- else:
32
- print(f"{REPO_NAME} repository already exists. Checking for updates...")
33
- try:
34
- # Change to the repository directory to pull updates
35
- os.chdir(REPO_PATH)
36
- subprocess.run(["git", "pull"], check=True)
37
- print("Repository updated successfully.")
38
- os.chdir("..") # Change back to original directory
39
- except subprocess.CalledProcessError as e:
40
- print(f"Error updating repository: {e}")
41
- raise
42
-
43
- # Change to the repository directory for script execution
44
- os.chdir(REPO_PATH)
45
-
46
-
47
- def run_inference(
48
- prompt: str,
49
- stable_diffusion_model: str,
50
- num_inference_steps: int,
51
- guidance_scale: float,
52
- model_precision_type: str,
53
- seed: int,
54
- filename: str,
55
- model_3d: bool,
56
- verbose: bool,
57
- ):
58
- """Runs the inference process for generating Minecraft skins."""
59
-
60
- sd_model_map = {
61
- '2': "minecraft-skins",
62
- 'xl': "minecraft-skins-sdxl",
63
- }
64
- sd_script = sd_model_map.get(stable_diffusion_model)
65
-
66
- if not sd_script:
67
- raise ValueError(f"Invalid stable_diffusion_model: {stable_diffusion_model}")
68
-
69
- command = [
70
- "python",
71
- f"Scripts/{sd_script}.py",
72
- prompt,
73
- str(num_inference_steps),
74
- str(guidance_scale),
75
- model_precision_type,
76
- str(seed),
77
- filename,
78
- ]
79
-
80
- if model_3d:
81
- command.append("--model_3d")
82
- if verbose:
83
- command.append("--verbose")
84
-
85
- try:
86
- # Use subprocess.run for better control and error handling
87
- result = subprocess.run(command, capture_output=True, text=True, check=True)
88
- print("Inference command output:")
89
- print(result.stdout)
90
- if result.stderr:
91
- print("Inference command error output:")
92
- print(result.stderr)
93
-
94
- except subprocess.CalledProcessError as e:
95
- print(f"Error during inference: {e}")
96
- print(f"Stdout: {e.stdout}")
97
- print(f"Stderr: {e.stderr}")
98
- return None, None # Return None for outputs on error
99
- except Exception as e:
100
- print(f"An unexpected error occurred: {e}")
101
- return None, None
102
-
103
- # Ensure output directory exists
104
- OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
105
-
106
- # Construct output paths using pathlib
107
- image_path = OUTPUT_DIR / filename
108
- model_3d_path = OUTPUT_DIR / f"{filename.split('.')[0]}_3d_model.glb" if model_3d else None
109
-
110
- # Basic check for file existence (can be more robust)
111
- if not image_path.exists():
112
- print(f"Warning: Image file not found at {image_path}")
113
- image_path = None
114
- if model_3d and model_3d_path and not model_3d_path.exists():
115
- print(f"Warning: 3D model file not found at {model_3d_path}")
116
- model_3d_path = None
117
-
118
- return str(image_path) if image_path else None, str(model_3d_path) if model_3d_path else None
119
-
120
-
121
- def create_gradio_ui():
122
- """Defines and returns the Gradio UI components."""
123
- with gr.Blocks(title="Minecraft Skin Generator", css=".pixelated {image-rendering: pixelated} .checkered img {background-image: url(\'data:image/svg+xml,<svg xmlns=\'http://www.w3.org/2000/svg\' width=\'2\' height=\'2\' fill-opacity=\'.15\'><rect x=\'1\' width=\'1\' height=\'1\'/><rect y=\'1\' width=\'1\' height=\'1\'/></svg>\');background-size: 16px;}") as imsteve:
124
- gr.Label("Minecraft Skin Generator")
125
- gr.Markdown("Make AI generated Minecraft Skins by a Finetuned Stable Diffusion Version!<br>\nGithub Repository & Model used: https://github.com/Nick088Official/Minecraft_Skin_Generator<br>\n**Credits:**\n [Monadical-SAS](https://github.com/Monadical-SAS/minecraft_skin_generator)\n (Creators of the model), [Nick088](https://linktr.ee/Nick088) (Improving usage of the model)\n daroche (helping fix the 3d model texture isue)\n [Brottweiler](https://gist.github.com/Brottweiler/483d0856c6692ef70cf90bf1a85ce364)(script to fix the 3d model texture)\n [not-holar](https://huggingface.co/not-holar) (made the rendering of the image asset in the web ui look pixelated like minecraft and have a checkered background)\n[meew](https://huggingface.co/spaces/meeww/Minecraft_Skin_Generator/blob/main/models/player_model.glb) (Minecraft Player 3d model) <br>\n [![Discord](https://img.shields.io/discord/1198701940511617164?color=%23738ADB&label=Discord&style=for-the-badge)](https://discord.gg/AQsmBmgEPy)")
126
-
127
- with gr.Row():
128
- prompt = gr.Textbox(label="Your Prompt", info="What the Minecraft Skin should look like")
129
- stable_diffusion_model = gr.Dropdown(['2', 'xl'], value="xl", label="Stable Diffusion Model", info="Choose which Stable Diffusion Model to use, xl understands prompts better")
130
- model_precision_type = gr.Dropdown(["fp16", "fp32"], value="fp16", label="Model Precision Type", info="The precision type to load the model, like fp16 which is faster, or fp32 which is more precise but more resource consuming")
131
-
132
- with gr.Row():
133
- num_inference_steps = gr.Slider(label="Number of Inference Steps", info="The number of denoising steps of the image. More denoising steps usually lead to a higher quality image at the cost of slower inference", minimum=1, maximum=50, value=25, step=1)
134
- guidance_scale = gr.Slider(label="Guidance Scale", info="Controls how much the image generation process follows the text prompt. Higher values make the image stick more closely to the input text.", minimum=0.0, maximum=10.0, value=7.5, step=0.1)
135
- seed = gr.Slider(value=42, minimum=0, maximum=MAX_SEED, step=1, label="Seed", info="A starting point to initiate the generation process, put 0 for a random one")
136
 
137
- filename = gr.Textbox(label="Output Image Name", info="The name of the file of the output image skin, keep the.png", value="output-skin.png")
138
- with gr.Row():
139
- model_3d = gr.Checkbox(label="See as 3D Model too", info="View the generated skin as a 3D Model too", value=True)
140
- verbose = gr.Checkbox(label="Verbose Output", info="Produce more detailed output while running", value=False)
141
 
142
- generate_skn = gr.Button("Generate")
143
- image_output = gr.Image(label="Generated Minecraft Skin Image Asset")
144
- image3d_output = gr.Model3D(clear_color=[0.0, 0.0, 0.0, 0.0], label="3D Model View of the Skin")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
 
146
- generate_skn.click(
147
- fn=run_inference,
148
- inputs=[
149
- prompt,
150
- stable_diffusion_model,
151
- num_inference_steps,
152
- guidance_scale,
153
- model_precision_type,
154
- seed,
155
- filename,
156
- model_3d,
157
- verbose,
158
- ],
159
- outputs=[
160
- image_output,
161
- image3d_output,
162
- ],
163
- )
164
- return imsteve
165
-
166
- def main():
167
- # Handle Hugging Face Spaces environment
168
- if os.environ.get("HF_TOKEN") or os.environ.get("HF_HOME") or os.environ.get("HUGGINGFACE_HUB_CACHE"):
169
- import spaces
170
- @spaces.GPU(duration=75)
171
- def wrapped_create_gradio_ui():
172
- return create_gradio_ui()
173
- demo = wrapped_create_gradio_ui()
174
- else:
175
- demo = create_gradio_ui()
176
-
177
- setup_repository()
178
- demo.launch(show_api=True, share=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179
 
180
  if __name__ == "__main__":
181
- main()
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import os
 
 
3
  from pathlib import Path
4
+ from utils import setup_repository, run_inference
5
 
6
+ # Ensure output directory exists
 
 
7
  OUTPUT_DIR = Path("output_minecraft_skins")
8
+ OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
9
+
10
+ # Custom CSS for Minecraft pixelated look and checkered background
11
+ CUSTOM_CSS = """
12
+ .pixelated { image-rendering: pixelated; image-rendering: -moz-crisp-edges; image-rendering: crisp-edges; }
13
+ .checkered {
14
+ background-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><rect fill="%23ddd" width="8" height="8"/><rect fill="%23ddd" x="8" y="8" width="8" height="8"/><rect fill="%23bbb" x="8" width="8" height="8"/><rect fill="%23bbb" y="8" width="8" height="8"/></svg>');
15
+ background-size: 16px;
16
+ }
17
+ #mc-skin { max-width: 400px; margin: auto; }
18
+ #mc-model { height: 500px; }
19
+ .sidebar { background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%); }
20
+ """
21
+
22
+ def random_seed():
23
+ """Generate a random seed."""
24
+ import numpy as np
25
+ return np.random.randint(0, np.iinfo(np.int32).max)
26
+
27
+ def clear_all():
28
+ """Clear all outputs."""
29
+ return None, None, gr.Gallery(visible=False), []
30
+
31
+ with gr.Blocks(
32
+ title="Minecraft Skin Generator",
33
+ theme=gr.themes.Soft(primary_hue="green", secondary_hue="emerald"),
34
+ css=CUSTOM_CSS,
35
+ fill_height=True
36
+ ) as demo:
37
+ gr.Markdown(
38
+ """
39
+ # πŸš€ Minecraft Skin Generator
40
+ **Built with [anycoder](https://huggingface.co/spaces/akhaliq/anycoder)**
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
+ Make AI generated Minecraft Skins using finetuned Stable Diffusion models! πŸŽ¨πŸ‘¨β€πŸ’Ό
 
 
 
43
 
44
+ [GitHub Repo](https://github.com/BF667/Minecraft_Skin_Generator) | [Discord](https://discord.gg/AQsmBmgEPy)
45
+ """
46
+ )
47
+
48
+ gr.Markdown(
49
+ """
50
+ Credits: [Monadical-SAS](https://github.com/Monadical-SAS/minecraft_skin_generator), [Nick088](https://linktr.ee/Nick088), and more!
51
+ """
52
+ )
53
+
54
+ state = gr.State(value=[]) # For gallery history
55
+
56
+ with gr.Row():
57
+ with gr.Column(scale=1):
58
+ with gr.Accordion("πŸŽ›οΈ Generation Settings", open=True):
59
+ prompt = gr.Textbox(
60
+ label="Prompt",
61
+ placeholder="e.g., steve with diamond armor, cyberpunk creeper",
62
+ lines=2,
63
+ scale=3
64
+ )
65
+ with gr.Row():
66
+ model_dropdown = gr.Dropdown(
67
+ choices=["xl", "2"],
68
+ value="xl",
69
+ label="Model",
70
+ info="XL understands prompts better"
71
+ )
72
+ precision_dropdown = gr.Dropdown(
73
+ choices=["fp16", "fp32"],
74
+ value="fp16",
75
+ label="Precision"
76
+ )
77
+ with gr.Row():
78
+ steps_slider = gr.Slider(1, 50, value=25, step=1, label="Inference Steps")
79
+ guidance_slider = gr.Slider(0.0, 10.0, value=7.5, step=0.1, label="Guidance Scale")
80
+ with gr.Row():
81
+ seed_slider = gr.Slider(0, 2147483647, value=42, step=1, label="Seed", interactive=True)
82
+ random_btn = gr.Button("🎲 Random Seed", scale=0, min_width=120)
83
+ filename_tb = gr.Textbox("output-skin.png", label="Filename (.png)", interactive=True)
84
+ gen_btn = gr.Button("Generate Skin! πŸš€", variant="primary", scale=2)
85
+ adv_cb = gr.CheckboxGroup(
86
+ choices=["3D Model", "Verbose"],
87
+ label="Advanced Options",
88
+ value=["3D Model"]
89
+ )
90
+
91
+ gr.Examples(
92
+ examples=[
93
+ ["steve with diamond armor"],
94
+ ["alex as cyberpunk hacker"],
95
+ ["creeper with sunglasses"],
96
+ ["enderman in space suit"],
97
+ ["zombie knight armor"]
98
+ ],
99
+ inputs=prompt
100
+ )
101
+
102
+ gr.Markdown("### πŸ“± Cool Features")
103
+ gr.Markdown("""
104
+ - **Pixelated Minecraft Style** preview
105
+ - **3D Model Viewer** with rotations
106
+ - **Random Seed** for variety
107
+ - **History Gallery** of generations
108
+ - **Batch Mode** coming soon!
109
+ """)
110
 
111
+ with gr.Column(scale=2):
112
+ with gr.Group(elem_classes="checkered"):
113
+ skin_img = gr.Image(
114
+ label="Generated Skin",
115
+ elem_id="mc-skin",
116
+ elem_classes="pixelated"
117
+ )
118
+ model_3d = gr.Model3D(
119
+ label="3D Preview",
120
+ clear_color=[0.1, 0.2, 0.3, 1.0],
121
+ elem_id="mc-model"
122
+ )
123
+ gallery = gr.Gallery(
124
+ label="Generation History",
125
+ columns=3,
126
+ height=300,
127
+ visible=True
128
+ )
129
+
130
+ # Events
131
+ random_btn.click(random_seed, outputs=seed_slider)
132
+
133
+ gen_btn.click(
134
+ fn=run_inference,
135
+ inputs=[
136
+ prompt,
137
+ model_dropdown,
138
+ steps_slider,
139
+ guidance_slider,
140
+ precision_dropdown,
141
+ seed_slider,
142
+ filename_tb,
143
+ gr.State(lambda x: "3D Model" in x)(adv_cb),
144
+ gr.State(lambda x: "Verbose" in x)(adv_cb)
145
+ ],
146
+ outputs=[skin_img, model_3d],
147
+ api_name="generate_skin",
148
+ api_visibility="public",
149
+ show_progress="full"
150
+ ).then(
151
+ fn=lambda img_path, history: (history + [img_path] if img_path else history)[:12],
152
+ inputs=[skin_img, state],
153
+ outputs=[gallery, state]
154
+ )
155
+
156
+ # Clear button
157
+ gr.ClearButton([prompt, skin_img, model_3d, gallery, state], value="πŸ—‘οΈ Clear All")
158
+
159
+ # Examples click
160
+ gr.Examples(
161
+ examples=[
162
+ ["steve with diamond armor"],
163
+ ["alex as cyberpunk hacker"],
164
+ ["creeper with sunglasses"],
165
+ ["enderman in space suit"],
166
+ ["zombie knight armor"]
167
+ ],
168
+ inputs=[prompt],
169
+ examples_per_page=5,
170
+ run_on_click=True
171
+ )
172
+
173
+ # Setup repo on load
174
+ demo.load(setup_repository)
175
 
176
  if __name__ == "__main__":
177
+ demo.launch(
178
+ server_name="0.0.0.0",
179
+ server_port=7860,
180
+ share=True,
181
+ footer_links=[
182
+ {"label": "Built with anycoder", "url": "https://huggingface.co/spaces/akhaliq/anycoder"},
183
+ "api",
184
+ "gradio"
185
+ ]
186
+ )
requirements.txt CHANGED
@@ -1,7 +1,10 @@
1
- torch
2
- transformers
3
- diffusers
4
- accelerate
5
- gradio==5.29.1
 
 
6
  scipy
7
- Pillow
 
 
1
+ gradio
2
+ numpy
3
+ requests
4
+ Pillow
5
+ pandas
6
+ matplotlib
7
+ plotly
8
  scipy
9
+ scikit-learn
10
+ joblib