KazuX-1 commited on
Commit
e918b7d
Β·
1 Parent(s): 36488c1

Add application file

Browse files
Files changed (2) hide show
  1. app.py +191 -0
  2. requirements.txt +7 -0
app.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from diffusers import StableDiffusionPipeline # ← Ganti ke StableDiffusionPipeline
4
+ import gc
5
+ import time
6
+ import os
7
+
8
+ print("=" * 50)
9
+ print("πŸš€ Starting Image Generator on Hugging Face Free Tier")
10
+ print("=" * 50)
11
+
12
+ # MODEL YANG PASTI BISA dan MASIH AKTIF
13
+ MODEL_ID = "CompVis/stable-diffusion-v1-4"
14
+
15
+ print(f"πŸ“¦ Loading model: {MODEL_ID}")
16
+ print("⚠️ Download model ~1.7GB, butuh 3-5 menit... SABAR YA!")
17
+
18
+ device = "cuda" if torch.cuda.is_available() else "cpu"
19
+ print(f"πŸ’» Device: {device}")
20
+
21
+ # Clean memory
22
+ gc.collect()
23
+ if device == "cuda":
24
+ torch.cuda.empty_cache()
25
+
26
+ # Load model
27
+ try:
28
+ start_time = time.time()
29
+
30
+ # Gunakan StableDiffusionPipeline, bukan DiffusionPipeline
31
+ pipe = StableDiffusionPipeline.from_pretrained(
32
+ MODEL_ID,
33
+ torch_dtype=torch.float16 if device == "cuda" else torch.float32,
34
+ use_safetensors=True,
35
+ safety_checker=None, # Matikan safety checker untuk hemat memory
36
+ requires_safety_checker=False
37
+ )
38
+
39
+ # Enable memory optimizations
40
+ pipe.enable_attention_slicing()
41
+
42
+ if device == "cuda":
43
+ pipe = pipe.to(device)
44
+ pipe.enable_model_cpu_offload()
45
+ else:
46
+ print("⚠️ Running on CPU - akan lambat tapi stabil")
47
+ pipe.enable_vae_slicing()
48
+
49
+ load_time = time.time() - start_time
50
+ print(f"βœ… Model loaded in {load_time:.1f} seconds")
51
+ print("πŸŽ‰ Aplikasi siap digunakan!")
52
+
53
+ except Exception as e:
54
+ print(f"❌ Error loading model: {e}")
55
+ print("πŸ’‘ Cek LOGS di atas untuk detail error")
56
+ raise
57
+
58
+ def generate(prompt, negative_prompt, steps, guidance, width, height, seed):
59
+ """Generate image with optimal settings for free tier"""
60
+
61
+ print(f"\n🎨 Generating image...")
62
+ print(f"πŸ“ Prompt: {prompt[:50]}...")
63
+ print(f"βš™οΈ Settings: steps={steps}, guidance={guidance}, {width}x{height}")
64
+
65
+ start_time = time.time()
66
+
67
+ try:
68
+ # Pastikan resolusi multiple dari 8 (requirement SD)
69
+ width = (width // 8) * 8
70
+ height = (height // 8) * 8
71
+
72
+ # Batasi resolusi untuk free tier CPU
73
+ if device == "cpu":
74
+ if width > 640:
75
+ width = 640
76
+ if height > 640:
77
+ height = 640
78
+
79
+ generator = torch.manual_seed(seed) if seed != -1 else None
80
+
81
+ with torch.no_grad():
82
+ image = pipe(
83
+ prompt=prompt,
84
+ negative_prompt=negative_prompt,
85
+ num_inference_steps=steps,
86
+ guidance_scale=guidance,
87
+ width=width,
88
+ height=height,
89
+ generator=generator
90
+ ).images[0]
91
+
92
+ # Clean up memory
93
+ gc.collect()
94
+ if device == "cuda":
95
+ torch.cuda.empty_cache()
96
+
97
+ gen_time = time.time() - start_time
98
+ print(f"βœ… Generated in {gen_time:.1f} seconds")
99
+
100
+ return image
101
+
102
+ except Exception as e:
103
+ print(f"❌ Error: {e}")
104
+ return None
105
+
106
+ # Create the interface
107
+ with gr.Blocks(theme=gr.themes.Soft(), title="AI Image Generator Free") as demo:
108
+ gr.Markdown("""
109
+ # 🎨 AI Image Generator - Free Tier
110
+
111
+ **Model:** Stable Diffusion 1.4 (CompVis) βœ… Public & Active
112
+ **Status:** Siap digunakan!
113
+
114
+ ⚑ **Tips untuk hasil terbaik:**
115
+ - Gunakan resolusi **512x512** untuk kecepatan optimal di CPU
116
+ - **Steps 15-20** adalah sweet spot (cepat + quality cukup)
117
+ - Hasil akan muncul dalam **1-3 menit** (CPU Free Tier)
118
+ """)
119
+
120
+ with gr.Row():
121
+ with gr.Column(scale=1):
122
+ prompt = gr.Textbox(
123
+ label="πŸ“ Prompt",
124
+ placeholder="Describe the image you want to generate...",
125
+ lines=3,
126
+ value="a beautiful sunset over mountains, digital art, highly detailed"
127
+ )
128
+
129
+ negative_prompt = gr.Textbox(
130
+ label="❌ Negative Prompt",
131
+ value="blurry, low quality, bad anatomy, distorted, ugly, worst quality, deformed",
132
+ lines=2
133
+ )
134
+
135
+ with gr.Row():
136
+ steps = gr.Slider(
137
+ 10, 30, value=18, step=1,
138
+ label="πŸ”„ Steps (15-20 recommended)"
139
+ )
140
+ guidance = gr.Slider(
141
+ 1, 15, value=7.0, step=0.5,
142
+ label="🎯 Guidance Scale"
143
+ )
144
+
145
+ with gr.Row():
146
+ width = gr.Dropdown(
147
+ [384, 512, 640], # Hapus 768 karena terlalu berat untuk CPU
148
+ value=512,
149
+ label="πŸ“ Width"
150
+ )
151
+ height = gr.Dropdown(
152
+ [384, 512, 640],
153
+ value=512,
154
+ label="πŸ“ Height"
155
+ )
156
+
157
+ seed = gr.Number(
158
+ value=-1,
159
+ label="🎲 Seed (-1 for random)",
160
+ precision=0
161
+ )
162
+
163
+ btn = gr.Button("πŸš€ Generate Image", variant="primary", size="lg")
164
+
165
+ with gr.Column(scale=1):
166
+ output = gr.Image(label="✨ Generated Image", height=450)
167
+
168
+ # Examples
169
+ gr.Examples(
170
+ examples=[
171
+ ["a beautiful sunset over mountains, digital art, vibrant colors", "blurry, low quality", 18, 7.0, 512, 512, -1],
172
+ ["a majestic lion in the savanna, wildlife photography", "blurry, low quality", 20, 7.5, 512, 512, -1],
173
+ ["a futuristic city with flying cars, cyberpunk style", "blurry, ugly, low quality", 20, 7.5, 512, 512, 42],
174
+ ["a cute puppy playing in grass, photorealistic", "cartoon, anime, blurry", 15, 7.0, 512, 512, -1],
175
+ ],
176
+ inputs=[prompt, negative_prompt, steps, guidance, width, height, seed],
177
+ label="Click any example to test πŸ‘†"
178
+ )
179
+
180
+ gr.Markdown("""
181
+ ---
182
+ **ℹ️ Info:**
183
+ - βœ… **Model:** CompVis/stable-diffusion-v1-4 (Public, No Login)
184
+ - πŸš€ Loading model: 2-4 menit (first time only)
185
+ - ⏱️ Generate image: 1-3 menit (CPU Free Tier)
186
+ - πŸ’Ύ Pastikan requirements.txt sudah sesuai
187
+ """)
188
+
189
+ if __name__ == "__main__":
190
+ print("πŸš€ Launching Gradio app...")
191
+ demo.launch(server_name="0.0.0.0", server_port=7860)
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ diffusers==0.27.2
2
+ transformers==4.38.2
3
+ accelerate==0.27.2
4
+ safetensors==0.4.2
5
+ sentencepiece==0.1.99
6
+ torch==2.2.1
7
+ gradio==4.19.2