VamooseBambel commited on
Commit
00f2e78
·
verified ·
1 Parent(s): c303c94

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +194 -0
app.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import yaml
3
+ import subprocess
4
+ import sys
5
+ import spaces
6
+ import numpy as np
7
+ from nsfw_detector import NSFWDetector, create_error_image
8
+ from PIL import Image
9
+ import time
10
+ import logging
11
+ from threading import Timer
12
+
13
+ logging.basicConfig(level=logging.INFO)
14
+ logger = logging.getLogger(__name__)
15
+
16
+ # Global variables
17
+ global_model = None
18
+ last_use_time = None
19
+ unload_timer = None
20
+ TIMEOUT_SECONDS = 120 # 2 minutes
21
+
22
+ # Clone the repository
23
+ if not os.path.exists('Sana'):
24
+ subprocess.run(['git', 'clone', 'https://github.com/NVlabs/Sana.git'])
25
+
26
+ # Change to Sana directory
27
+ os.chdir('Sana')
28
+
29
+ # Workarounds
30
+ def modify_builder():
31
+ builder_path = 'diffusion/model/builder.py'
32
+ with open(builder_path, 'r') as f:
33
+ content = f.readlines()
34
+
35
+ # Find the text_encoder_dict definition
36
+ for i, line in enumerate(content):
37
+ if 'text_encoder_dict = {' in line:
38
+ content.insert(i + 11, ' "unsloth-gemma-2-2b-it": "unsloth/gemma-2-2b-it",\n')
39
+ break
40
+
41
+ with open(builder_path, 'w') as f:
42
+ f.writelines(content)
43
+
44
+ def modify_config():
45
+ config_path = 'configs/sana_config/1024ms/Sana_1600M_img1024.yaml'
46
+
47
+ with open(config_path, 'r') as f:
48
+ config = yaml.safe_load(f)
49
+
50
+ # Update text encoder
51
+ config['text_encoder']['text_encoder_name'] = 'unsloth-gemma-2-2b-it'
52
+
53
+ config['model']['mixed_precision'] = 'bf16'
54
+
55
+ with open(config_path, 'w') as f:
56
+ yaml.dump(config, f, default_flow_style=False)
57
+
58
+ # Run environment setup commands
59
+ setup_commands = [
60
+ "pip install torch", # init raw torch
61
+ "pip install -U pip", # update pip
62
+ "pip install -U xformers==0.0.27.post2 --index-url https://download.pytorch.org/whl/cu121", # fast attn
63
+ "pip install pyyaml",
64
+ "pip install -e ." # install sana
65
+ ]
66
+
67
+ for cmd in setup_commands:
68
+ print(f"Running: {cmd}")
69
+ subprocess.run(cmd.split())
70
+
71
+ import torch
72
+ import gradio as gr
73
+ sys.path.append('.')
74
+
75
+ # Modify config and builder before importing SanaPipeline
76
+ modify_config()
77
+ modify_builder()
78
+ from Sana.app.sana_pipeline import SanaPipeline
79
+
80
+ def unload_model():
81
+ global global_model, last_use_time
82
+ current_time = time.time()
83
+ if last_use_time and (current_time - last_use_time) >= TIMEOUT_SECONDS:
84
+ logger.info("Unloading model due to inactivity...")
85
+ global_model = None
86
+ torch.cuda.empty_cache()
87
+ return "Model unloaded due to inactivity"
88
+
89
+ def reset_timer():
90
+ global unload_timer, last_use_time
91
+ if unload_timer:
92
+ unload_timer.cancel()
93
+ last_use_time = time.time()
94
+ unload_timer = Timer(TIMEOUT_SECONDS, unload_model)
95
+ unload_timer.start()
96
+
97
+ @spaces.GPU(duration=110)
98
+ def generate_image(prompt, height, width, guidance_scale, pag_guidance_scale, num_inference_steps):
99
+ global global_model
100
+ try:
101
+ device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
102
+ if torch.cuda.is_available():
103
+ torch.cuda.empty_cache()
104
+
105
+ # Load model if needed
106
+ if global_model is None:
107
+ logger.info("Loading model...")
108
+ global_model = SanaPipeline("configs/sana_config/1024ms/Sana_1600M_img1024.yaml")
109
+ global_model.from_pretrained("hf://Efficient-Large-Model/Sana_1600M_1024px/checkpoints/Sana_1600M_1024px.pth")
110
+
111
+ reset_timer()
112
+ # Random seed
113
+ generator = torch.Generator(device=device).manual_seed(int(time.time()))
114
+
115
+ image = global_model(
116
+ prompt=prompt,
117
+ height=height,
118
+ width=width,
119
+ guidance_scale=guidance_scale,
120
+ pag_guidance_scale=pag_guidance_scale,
121
+ num_inference_steps=num_inference_steps,
122
+ generator=generator,
123
+ )
124
+
125
+ # Convert tensor to PIL Image
126
+ image = ((image[0] + 1) / 2).float().cpu()
127
+ image = (image * 255).clamp(0, 255).numpy().astype(np.uint8)
128
+ image = Image.fromarray(image.transpose(1, 2, 0))
129
+
130
+ # Check for NSFW content
131
+ detector = NSFWDetector()
132
+ is_nsfw, category, confidence = detector.check_image(image)
133
+
134
+ if category == "SAFE":
135
+ return image
136
+ else:
137
+ logger.warning(f"NSFW content detected ({category} with {confidence:.2f}% confidence)")
138
+ return create_error_image()
139
+
140
+ except Exception as e:
141
+ logger.error(f"Error in generate_image: {str(e)}")
142
+ raise gr.Error(f"Generation failed: {str(e)}")
143
+
144
+ # Gradio Interface
145
+ with gr.Blocks(theme=gr.themes.Default(), css=""".center-text {text-align: center;}
146
+ .footer-link {text-align: center; margin: 20px 0;}
147
+ .slider-pad {margin-bottom: 24px;}""") as interface:
148
+ with gr.Row(elem_id="banner"):
149
+ with gr.Column():
150
+ gr.Markdown("# Sana 1.6B", elem_classes="center-text")
151
+ gr.Markdown("Generate high-resolution images up to 4096x4096 using the Sana 1.6B model, fast.", elem_classes="center-text")
152
+
153
+ with gr.Row():
154
+ with gr.Column(scale=2):
155
+ prompt = gr.Textbox(label="Prompt", placeholder="Enter your prompt here...", lines=3)
156
+ with gr.Row():
157
+ with gr.Column():
158
+ height = gr.Slider(minimum=512, maximum=4096, step=64, value=1024, label="Height")
159
+ width = gr.Slider(minimum=512, maximum=4096, step=64, value=1024, label="Width")
160
+ with gr.Column():
161
+ guidance_scale = gr.Slider(minimum=1.0, maximum=10.0, step=0.5, value=5.0, label="Guidance Scale")
162
+ pag_guidance_scale = gr.Slider(minimum=1.0, maximum=5.0, step=0.1, value=2.0, label="PAG Guidance Scale")
163
+ num_inference_steps = gr.Slider(minimum=2, maximum=50, step=1, value=18, label="Number of Steps")
164
+
165
+ gr.Markdown("*Note: Higher guidance scales provide stronger adherence to the prompt. PAG guidance helps with image-text alignment.*")
166
+ gr.Markdown("⏱️ Be patient, the model loads into memory slow first time around.")
167
+
168
+ generate_btn = gr.Button("Generate", variant="primary")
169
+
170
+ with gr.Column(scale=2):
171
+ output = gr.Image(label="Generated Image", height=512)
172
+
173
+ # Examples section
174
+ gr.Examples(
175
+ examples=[
176
+ ["a cyberpunk cat with a neon sign that says 'Sana'", 1024, 1024, 5.0, 2.0, 18],
177
+ ["a beautiful sunset over a mountain landscape", 1024, 1024, 5.0, 2.0, 18],
178
+ ["a futuristic city with flying cars", 1024, 1024, 5.0, 2.0, 18]
179
+ ],
180
+ inputs=[prompt, height, width, guidance_scale, pag_guidance_scale, num_inference_steps],
181
+ outputs=output,
182
+ fn=generate_image,
183
+ )
184
+
185
+ generate_btn.click(
186
+ fn=generate_image,
187
+ inputs=[prompt, height, width, guidance_scale, pag_guidance_scale, num_inference_steps],
188
+ outputs=output
189
+ )
190
+
191
+ gr.Markdown("[link to model](https://huggingface.co/Efficient-Large-Model/Sana_1600M_1024px)", elem_classes="center-text footer-link")
192
+
193
+ # Launch the interface
194
+ interface.launch()