DigiP-AI commited on
Commit
312a433
Β·
verified Β·
1 Parent(s): 4eee1a2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +148 -0
app.py CHANGED
@@ -86,6 +86,154 @@ with gr.Blocks(theme=theme, elem_id="app-container") as app:
86
 
87
  submit_btn.click(feifeichat, [input_img], [output_text])
88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
 
90
  if __name__ == "__main__":
91
  app.launch()
 
86
 
87
  submit_btn.click(feifeichat, [input_img], [output_text])
88
 
89
+ # Project by Nymbo
90
+ # Edited by DigiP-AI
91
+
92
+ API_URL = "https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-3.5-large-turbo"
93
+ API_TOKEN = os.getenv("HF_READ_TOKEN")
94
+ headers = {"Authorization": f"Bearer {API_TOKEN}"}
95
+ timeout = 100
96
+
97
+ # Function to clear input and output
98
+ def clear():
99
+ return None
100
+
101
+ # Function to query the API and return the generated image
102
+ def query(prompt, is_negative=False, steps=35, cfg_scale=7, sampler="DPM++ 2M Karras", seed=-1, strength=0.7, width=896, height=1152):
103
+ if prompt == "" or prompt is None:
104
+ return None
105
+
106
+ key = random.randint(0, 999)
107
+
108
+ API_TOKEN = random.choice([os.getenv("HF_READ_TOKEN")])
109
+ headers = {"Authorization": f"Bearer {API_TOKEN}"}
110
+
111
+ # Translate the prompt from Russian to English if necessary
112
+ prompt = GoogleTranslator(source='ru', target='en').translate(prompt)
113
+ print(f'\033[1mGeneration {key} translation:\033[0m {prompt}')
114
+
115
+ # Add some extra flair to the prompt
116
+ prompt = f"{prompt} | ultra detail, ultra elaboration, ultra quality, perfect."
117
+ print(f'\033[1mGeneration {key}:\033[0m {prompt}')
118
+
119
+ # Prepare the payload for the API call, including width and height
120
+ payload = {
121
+ "inputs": prompt,
122
+ "is_negative": is_negative,
123
+ "steps": steps,
124
+ "cfg_scale": cfg_scale,
125
+ "seed": seed if seed != -1 else random.randint(1, 1000000000),
126
+ "strength": strength,
127
+ "parameters": {
128
+ "width": width, # Pass the width to the API
129
+ "height": height # Pass the height to the API
130
+ }
131
+ }
132
+
133
+ # Send the request to the API and handle the response
134
+ response = requests.post(API_URL, headers=headers, json=payload, timeout=timeout)
135
+ if response.status_code != 200:
136
+ print(f"Error: Failed to get image. Response status: {response.status_code}")
137
+ print(f"Response content: {response.text}")
138
+ if response.status_code == 503:
139
+ raise gr.Error(f"{response.status_code} : The model is being loaded")
140
+ raise gr.Error(f"{response.status_code}")
141
+
142
+ try:
143
+ # Convert the response content into an image
144
+ image_bytes = response.content
145
+ image = Image.open(io.BytesIO(image_bytes))
146
+ print(f'\033[1mGeneration {key} completed!\033[0m ({prompt})')
147
+ return image
148
+ except Exception as e:
149
+ print(f"Error when trying to open the image: {e}")
150
+ return None
151
+
152
+ examples = [
153
+ "a beautiful woman with blonde hair and blue eyes",
154
+ "a beautiful woman with brown hair and grey eyes",
155
+ "a beautiful woman with black hair and brown eyes",
156
+ ]
157
+
158
+ # CSS to style the app
159
+ css = """
160
+ footer{display:none !important}
161
+ #app-container {
162
+ max-width: 930px;
163
+ margin-left: auto;
164
+ margin-right: auto;
165
+ }
166
+ """
167
+
168
+ # Build the Gradio UI with Blocks
169
+ with gr.Blocks(theme=theme, css=css) as app:
170
+ # Add a title to the app
171
+ gr.HTML("<center><h1>🎨 Stable Diffusion 3.5 large turbo πŸ‡¬πŸ‡§</h1></center>")
172
+ with gr.Tabs() as tabs:
173
+ with gr.TabItem("Text to Image"):
174
+ # Container for all the UI elements
175
+ with gr.Column(elem_id="app-container"):
176
+ # Add a text input for the main prompt
177
+ with gr.Row():
178
+ with gr.Column(elem_id="prompt-container"):
179
+ with gr.Group():
180
+ with gr.Row():
181
+ text_prompt = gr.Textbox(label="Image Prompt ✍️", placeholder="Enter a prompt here", lines=2, show_copy_button = True, elem_id="prompt-text-input")
182
+
183
+ # Accordion for advanced settings
184
+ with gr.Row():
185
+ with gr.Accordion("Advanced Settings", open=False):
186
+ negative_prompt = gr.Textbox(label="Negative Prompt", lines=4, placeholder="What should not be in the image", value="(hands:-1.25), physical-defects:2, unhealthy-deformed-joints:2, unhealthy-hands:2, out of frame, bad face, (bad-image-v2-39000:1.3), (((out of frame))), deformed body features, poor facial details, (poorly drawn face:1.3), jpeg artifacts, (missing arms:1.1), (missing legs:1.1), (extra arms:1.2), (extra legs:1.2)")
187
+ with gr.Row():
188
+ width = gr.Slider(label="ImageWidth", value=896, minimum=64, maximum=1216, step=32)
189
+ height = gr.Slider(label="Image Height", value=1152, minimum=64, maximum=1216, step=32)
190
+ steps = gr.Slider(label="Sampling steps", value=50, minimum=1, maximum=100, step=1)
191
+ cfg = gr.Slider(label="CFG Scale", value=3.5, minimum=1, maximum=20, step=1)
192
+ strength = gr.Slider(label="PromptStrength", value=100, minimum=0, maximum=100, step=1)
193
+ seed = gr.Slider(label="Seed", value=-1, minimum=-1, maximum=1000000000, step=1) # Setting the seed to -1 will make it random
194
+ method = gr.Radio(label="Sampling method", value="DPM++ 2M Karras", choices=["DPM++ 2M Karras", "DPM++ 2S a Karras", "DPM2 a Karras", "DPM2 Karras", "DPM++ SDE Karras", "DEIS", "LMS", "DPM Adaptive", "DPM++ 2M", "DPM2 Ancestral", "DPM++ S", "DPM++ SDE", "DDPM", "DPM Fast", "dpmpp_2s_ancestral", "Euler", "Euler CFG PP", "Euler a", "Euler Ancestral", "Euler+beta", "Heun", "Heun PP2", "DDIM", "LMS Karras", "PLMS", "UniPC", "UniPC BH2"])
195
+ # Add a button to trigger the image generation
196
+ with gr.Row():
197
+ text_button = gr.Button("Generate Image 🎨", variant='primary', elem_id="gen-button")
198
+ clear_prompt =gr.Button("Clear Prompt πŸ—‘οΈ",variant="primary", elem_id="clear_button")
199
+ clear_prompt.click(lambda: (None), None, [text_prompt], queue=False, show_api=False)
200
+
201
+ with gr.Group():
202
+ # Image output area to display the generated image
203
+ with gr.Row():
204
+ image_output = gr.Image(type="pil", label="Image Output", format="png", show_share_button=False, elem_id="gallery")
205
+
206
+
207
+
208
+ gr.Examples(
209
+ examples = examples,
210
+ inputs = [text_prompt],
211
+ )
212
+
213
+ with gr.Row():
214
+ clear_results = gr.Button(value="Clear Image πŸ—‘οΈ", variant="primary", elem_id="clear_button")
215
+ clear_results.click(lambda: (None), None, [image_output], queue=False, show_api=False)
216
+
217
+ # Bind the button to the query function with the added width and height inputs
218
+ text_button.click(query, inputs=[text_prompt, negative_prompt, steps, cfg, method, seed, strength, width, height], outputs=image_output)
219
+
220
+
221
+ with gr.TabItem("Tips", visible=True):
222
+ with gr.Row():
223
+ gr.Markdown(
224
+ """
225
+ <div style="max-width: 650px; margin: 2rem auto; padding: 1rem; border-radius: 10px; background-color: #f0f0f0;">
226
+ <h2 style="font-size: 1.5rem; margin-bottom: 1rem;">How to Use</h2>
227
+ <ol style="padding-left: 1.5rem;">
228
+ <li>Enter a detailed description of the image you want to create.</li>
229
+ <li>Adjust advanced settings if desired (tap to expand).</li>
230
+ <li>Tap "Generate Image" and wait for your creation!</li>
231
+ </ol>
232
+ <p style="margin-top: 1rem; font-style: italic;">Tip: Be specific in your description for best results!</p>
233
+ </div>
234
+ """
235
+ )
236
+
237
 
238
  if __name__ == "__main__":
239
  app.launch()