tmblack commited on
Commit
2d91882
·
verified ·
1 Parent(s): d7154e8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +152 -177
app.py CHANGED
@@ -1,214 +1,189 @@
1
  import gradio as gr
2
- import re
3
- import os
4
- import requests
5
- import uuid
6
- import base64
7
- import traceback
8
 
9
- from share_btn import community_icon_html, loading_icon_html, share_js
 
 
10
 
11
- # সুরক্ষা ফিল্টারের জন্য ওয়ার্ড লিস্ট লোড করুন
12
- try:
13
- word_list_url = "https://huggingface.co/spaces/stabilityai/stable-diffusion/raw/main/list.txt"
14
- response = requests.get(word_list_url, timeout=10)
15
- response.raise_for_status()
16
- word_list = response.text.splitlines()
17
- print(f"সফলভাবে {len(word_list)} টি ফিল্টার শব্দ লোড হয়েছে")
18
- except Exception as e:
19
- print(f"ওয়ার্ড লিস্ট লোড করতে ব্যর্থ: {str(e)}")
20
- word_list = [] # ফিল্টার শব্দ লোড না হলে খালি লিস্ট ব্যবহার করুন
21
 
22
- def infer(prompt, negative, scale):
23
- # সুরক্ষা ফিল্টার চেক
24
- for filter_word in word_list:
25
- if re.search(rf"\b{filter_word}\b", prompt, re.IGNORECASE):
26
- print(f"অনুপযুক্ত শব্দ সনাক্ত হয়েছে: {filter_word}")
27
- print(f"প্রম্পট: {prompt}")
28
- raise gr.Error("অনিরাপদ কন্টেন্ট পাওয়া গেছে! অন্য প্রম্পট ব্যবহার করুন।")
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
- # ব্যাকএন্ড URL চেক
31
- url = os.getenv('JAX_BACKEND_URL')
32
- if not url:
33
- print("ব্যাকএন্ড URL সেট করা নেই!")
34
- raise gr.Error("ব্যাকএন্ড সার্ভার কনফিগার করা নেই।")
35
 
36
- print(f"ব্যাকএন্ড URL: {url}")
37
- print(f"প্রম্পট: {prompt}")
38
- print(f"নেগেটিভ: {negative}")
39
- print(f"স্কেল: {scale}")
 
 
 
 
 
 
 
 
 
40
 
41
- # ব্যাকএন্ডে রিকোয়েস্ট পাঠান
42
- try:
43
- payload = {'prompt': prompt, 'negative_prompt': negative, 'guidance_scale': scale}
44
- response = requests.post(url, json=payload, timeout=120)
45
- response.raise_for_status()
46
- response_data = response.json()
47
-
48
- # ইমেজ প্রসেসিং
49
- images = []
50
- for img_data in response_data["images"]:
51
- file_path = f"{uuid.uuid4()}.jpg"
52
- with open(file_path, "wb") as f:
53
- f.write(base64.b64decode(img_data))
54
- images.append(file_path)
55
-
56
- print(f"{len(images)} টি ইমেজ জেনারেট হয়েছে")
57
- return images
58
-
59
- except requests.exceptions.RequestException as e:
60
- error_msg = f"ব্যাকএন্ডে সংযোগ ব্যর্থ: {str(e)}"
61
- print(error_msg)
62
- raise gr.Error(error_msg)
63
- except (KeyError, ValueError) as e:
64
- error_msg = f"ব্যাকএন্ড থেকে ভুল রেসপন্স: {str(e)}"
65
- print(error_msg)
66
- print(f"রেসপন্স: {response.text[:500]}...")
67
- raise gr.Error("ইমেজ জেনারেট করতে ব্যর্থ। আবার চেষ্টা করুন।")
68
- except Exception as e:
69
- error_msg = f"অপ্রত্যাশিত ত্র���টি: {str(e)}"
70
- traceback.print_exc()
71
- raise gr.Error(error_msg)
72
-
73
- # UI স্টাইলিং
74
- css = """
75
- .gradio-container {
76
- max-width: 768px !important;
77
- font-family: 'IBM Plex Sans', sans-serif;
78
- }
79
- .gr-button {
80
- color: white !important;
81
- background: black !important;
82
- }
83
- input[type='range'] {
84
- accent-color: black;
85
- }
86
- #gallery {
87
- min-height: 22rem;
88
- margin-bottom: 15px;
89
- border-radius: .5rem !important;
90
- }
91
- #share-btn-container {
92
- display: flex;
93
- background-color: #000000;
94
- justify-content: center;
95
- align-items: center;
96
- border-radius: 9999px !important;
97
- width: 13rem;
98
- margin-top: 10px;
99
- margin-left: auto;
100
- }
101
- .footer {
102
- margin: 35px 0;
103
- text-align: center;
104
- border-top: 1px solid #e5e5e5;
105
- }
106
- .animate-spin {
107
- animation: spin 1s linear infinite;
108
- }
109
- @keyframes spin {
110
- from { transform: rotate(0deg); }
111
- to { transform: rotate(360deg); }
112
- }
113
- """
114
 
115
  # উদাহরণ প্রম্পট
116
  examples = [
117
- ['একটি সুউচ্চ তুষারাবৃত পর্বতের চূড়ায় ছোট কাঠের কুটির', 'নিম্ন গুণগতমান, অস্পষ্ট', 9],
118
- ['ভবিষ্যতের নগরীতে উড়ন্ত গাড়ি', 'মানুষ, বিকৃত', 9],
119
- ['সমুদ্রের নীচে সূর্যাস্ত দৃশ্য', 'টেক্সট, লোগো', 9],
120
- ['ফুলের বাগানে বসে থাকা একটি সিংহ', 'রিয়েলিস্টিক, ফটো', 9],
121
- ['কাচের গম্বুজের ভিতর মহাকাশ স্টেশন', 'অন্ধকার, ভয়ঙ্কর', 9]
122
  ]
123
 
124
- # Gradio ব্লক তৈরি
125
- with gr.Blocks(css=css) as block:
126
- # হেডার
127
- gr.HTML("""
128
- <div style="text-align: center;">
129
- <h1 style="font-weight: 900; margin: 10px 0;">
130
- Stable Diffusion 2.1 - বাংলা
131
- </h1>
132
- <p>
133
- টেক্সট থেকে ইমেজ জেনারেটর। আপনার মনের ছবি লিখুন, AI এটা বানিয়ে দেবে!
134
- </p>
135
- </div>
136
  """)
137
 
138
- # ইনপুট সেকশন
139
  with gr.Row():
140
  with gr.Column(scale=3):
141
- prompt_input = gr.Textbox(
142
- label="প্রম্পট লিখুন",
143
- placeholder="আপনার ইচ্ছামত ছবির বর্ণনা লিখুন...",
144
- lines=2
 
145
  )
146
- negative_input = gr.Textbox(
147
- label="এড়াতে চান এমন বিষয়",
148
- placeholder="যেসব বিষয় ছবিতে দেখতে চান না...",
149
  lines=1
150
  )
151
- with gr.Column(scale=1, min_width=150):
152
- generate_btn = gr.Button("ইমেজ তৈরি করুন", variant="primary")
153
 
154
- # আউটপুট গ্যালারী
155
  gallery = gr.Gallery(
156
- label="জেনারেটেড ইমেজসমূহ",
157
- columns=[2],
158
  height="auto",
159
- preview=True
 
160
  )
161
 
162
- # এডভান্সড সেটিংস
163
- with gr.Accordion("উন্নত সেটিংস", open=False):
164
- scale_slider = gr.Slider(
165
- label="গাইডেন্স স্কেল",
166
- minimum=0, maximum=20, value=9, step=0.1
167
- )
168
-
169
- # শেয়ার বাটন
170
- with gr.Group():
171
- gr.HTML(community_icon_html)
172
- gr.HTML(loading_icon_html)
173
- share_btn = gr.Button("কমিউনিটিতে শেয়ার করুন")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
174
 
175
- # উদাহরণ
176
  gr.Examples(
177
  examples=examples,
178
- inputs=[prompt_input, negative_input, scale_slider],
179
- outputs=gallery,
180
- fn=infer,
181
- cache_examples=False
182
  )
183
 
184
  # ইভেন্ট হ্যান্ডলার
185
- prompt_input.submit(
186
- fn=infer,
187
- inputs=[prompt_input, negative_input, scale_slider],
188
- outputs=gallery
189
- )
190
  generate_btn.click(
191
- fn=infer,
192
- inputs=[prompt_input, negative_input, scale_slider],
193
- outputs=gallery,
194
- concurrency_limit=3
 
 
 
 
 
 
 
 
 
195
  )
196
- share_btn.click(None, [], [], js=share_js)
197
 
198
- # ফুটার
199
- gr.HTML("""
200
- <div class="footer">
201
- <p>
202
- Powered by <a href="https://huggingface.co/stabilityai">StabilityAI</a>
203
- and <a href="https://huggingface.co/spaces">Hugging Face Spaces</a>
204
- </p>
205
  </div>
206
  """)
207
 
208
  # অ্যাপ্লিকেশন চালু করুন
209
- block.launch(
210
- server_name="0.0.0.0",
211
- server_port=7860,
212
- show_error=True,
213
- debug=True
214
- )
 
1
  import gradio as gr
2
+ import random
3
+ import numpy as np
4
+ from diffusers import DiffusionPipeline
5
+ import torch
 
 
6
 
7
+ # ডিভাইস সেটআপ
8
+ device = "cuda" if torch.cuda.is_available() else "cpu"
9
+ model_repo_id = "stabilityai/sdxl-turbo"
10
 
11
+ # মডেল লোড করুন
12
+ pipe = DiffusionPipeline.from_pretrained(
13
+ model_repo_id,
14
+ torch_dtype=torch.float16 if device == "cuda" else torch.float32,
15
+ variant="fp16" if device == "cuda" else None,
16
+ use_safetensors=True
17
+ )
18
+ pipe = pipe.to(device)
 
 
19
 
20
+ # সেটিংস
21
+ MAX_SEED = np.iinfo(np.int32).max
22
+ MAX_IMAGE_SIZE = 1024
23
+ DEFAULT_NUM_IMAGES = 4
24
+
25
+ def generate_images(
26
+ prompt,
27
+ negative_prompt="",
28
+ seed=0,
29
+ randomize_seed=True,
30
+ width=768,
31
+ height=768,
32
+ guidance_scale=0.0,
33
+ num_inference_steps=2,
34
+ num_images=DEFAULT_NUM_IMAGES,
35
+ progress=gr.Progress(track_tqdm=True)
36
+ ):
37
+ # র‍্যান্ডম সিড জেনারেট করুন
38
+ if randomize_seed:
39
+ seed = random.randint(0, MAX_SEED)
40
 
41
+ # জেনারেটর তৈরি করুন
42
+ generator = torch.Generator(device=device).manual_seed(seed)
 
 
 
43
 
44
+ # একাধিক ইমেজ জেনারেট করুন
45
+ images = []
46
+ for _ in range(num_images):
47
+ image = pipe(
48
+ prompt=prompt,
49
+ negative_prompt=negative_prompt,
50
+ guidance_scale=guidance_scale,
51
+ num_inference_steps=num_inference_steps,
52
+ width=width,
53
+ height=height,
54
+ generator=generator,
55
+ ).images[0]
56
+ images.append(image)
57
 
58
+ return images, seed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
  # উদাহরণ প্রম্পট
61
  examples = [
62
+ "A cyberpunk cityscape at night, neon lights, rain",
63
+ "Majestic waterfall in a tropical forest, cinematic lighting",
64
+ "An astronaut floating in space, earth in background",
65
+ "A futuristic robot playing guitar in a jazz club",
66
+ "A magical forest with glowing mushrooms and fireflies"
67
  ]
68
 
69
+ # UI থিম
70
+ theme = gr.themes.Glass(
71
+ primary_hue="purple",
72
+ secondary_hue="blue",
73
+ font=[gr.themes.GoogleFont("Poppins")]
74
+ )
75
+
76
+ # UI তৈরি
77
+ with gr.Blocks(theme=theme, css="footer {visibility: hidden}") as demo:
78
+ gr.Markdown("""
79
+ # 🚀 SDXL-Turbo Image Generator
80
+ **Create 4 stunning AI images in seconds!** No API key required.
81
  """)
82
 
 
83
  with gr.Row():
84
  with gr.Column(scale=3):
85
+ prompt = gr.Textbox(
86
+ label="Prompt",
87
+ placeholder="Describe your image...",
88
+ lines=2,
89
+ max_lines=3
90
  )
91
+ negative_prompt = gr.Textbox(
92
+ label="Negative Prompt",
93
+ placeholder="What to exclude from the image...",
94
  lines=1
95
  )
96
+ with gr.Column(scale=1):
97
+ generate_btn = gr.Button(" Generate 4 Images", variant="primary")
98
 
 
99
  gallery = gr.Gallery(
100
+ label="Generated Images",
101
+ columns=4,
102
  height="auto",
103
+ preview=True,
104
+ object_fit="contain"
105
  )
106
 
107
+ with gr.Accordion("Advanced Settings", open=False):
108
+ with gr.Row():
109
+ seed = gr.Slider(
110
+ label="Seed",
111
+ minimum=0,
112
+ maximum=MAX_SEED,
113
+ step=1,
114
+ value=0
115
+ )
116
+ randomize_seed = gr.Checkbox(
117
+ label="Random Seed",
118
+ value=True
119
+ )
120
+ with gr.Row():
121
+ width = gr.Slider(
122
+ label="Width",
123
+ minimum=256,
124
+ maximum=MAX_IMAGE_SIZE,
125
+ step=32,
126
+ value=768
127
+ )
128
+ height = gr.Slider(
129
+ label="Height",
130
+ minimum=256,
131
+ maximum=MAX_IMAGE_SIZE,
132
+ step=32,
133
+ value=768
134
+ )
135
+ with gr.Row():
136
+ guidance_scale = gr.Slider(
137
+ label="Guidance Scale",
138
+ minimum=0.0,
139
+ maximum=10.0,
140
+ step=0.1,
141
+ value=0.0
142
+ )
143
+ num_inference_steps = gr.Slider(
144
+ label="Inference Steps",
145
+ minimum=1,
146
+ maximum=50,
147
+ step=1,
148
+ value=2
149
+ )
150
+ num_images = gr.Slider(
151
+ label="Number of Images",
152
+ minimum=1,
153
+ maximum=10,
154
+ step=1,
155
+ value=DEFAULT_NUM_IMAGES
156
+ )
157
 
 
158
  gr.Examples(
159
  examples=examples,
160
+ inputs=prompt,
161
+ label="Example Prompts"
 
 
162
  )
163
 
164
  # ইভেন্ট হ্যান্ডলার
 
 
 
 
 
165
  generate_btn.click(
166
+ fn=generate_images,
167
+ inputs=[
168
+ prompt,
169
+ negative_prompt,
170
+ seed,
171
+ randomize_seed,
172
+ width,
173
+ height,
174
+ guidance_scale,
175
+ num_inference_steps,
176
+ num_images
177
+ ],
178
+ outputs=[gallery, seed]
179
  )
 
180
 
181
+ gr.Markdown("""
182
+ <div style="text-align: center; margin-top: 20px; color: #666;">
183
+ Powered by SDXL-Turbo • No API key required • Runs on Hugging Face Spaces
 
 
 
 
184
  </div>
185
  """)
186
 
187
  # অ্যাপ্লিকেশন চালু করুন
188
+ if __name__ == "__main__":
189
+ demo.launch(server_name="0.0.0.0", server_port=7860)