Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,432 +1,76 @@
|
|
1 |
import gradio as gr
|
2 |
-
from huggingface_hub import HfApi, whoami, InferenceClient
|
3 |
-
from config import howManyModelsToUse,num_models,max_images,inference_timeout,MAX_SEED,thePrompt,preSetPrompt,negPreSetPrompt
|
4 |
-
from all_models import models
|
5 |
-
import asyncio
|
6 |
import os
|
7 |
-
import
|
8 |
-
from
|
9 |
-
import
|
10 |
-
import
|
11 |
-
import
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
return [gr.Image(None, label=m, visible=(m!='NA')) for m in choices_plus]
|
37 |
-
def random_choices():
|
38 |
-
import random
|
39 |
-
random.seed()
|
40 |
-
return random.choices(models, k=num_models)
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
url = "https://api-inference.huggingface.co/models/charliebaby2023/cybrpny"
|
47 |
-
headers = { "Authorization": f"Bearer {token}"}
|
48 |
-
response = requests.get(url, headers=headers)
|
49 |
-
print(response.status_code)
|
50 |
-
print(response.text)
|
51 |
-
|
52 |
-
|
53 |
-
load_fn(models,HF_TOKEN)
|
54 |
-
|
55 |
-
|
56 |
-
#client = InferenceClient( provider="hf-inference", api_key=HF_TOKEN,)
|
57 |
-
#image = client.text_to_image( "Astronaut riding a horse", model="charliebaby2023/cybrpny",)
|
58 |
-
#print(f"{image}")
|
59 |
-
model_id = "CompVis/stable-diffusion-v1-4-original"
|
60 |
-
endpoint = f"/models/{model_id}"
|
61 |
-
|
62 |
-
# === CONFIG ===
|
63 |
-
host = "api-inference.huggingface.co"
|
64 |
-
#endpoint = "/models/charliebaby2023/cybrpny"
|
65 |
-
#token = HF_TOKEN
|
66 |
-
prompt = "a futuristic city on Mars at sunset"
|
67 |
-
|
68 |
-
# === REQUEST SETUP ===
|
69 |
-
body = json.dumps({
|
70 |
-
"inputs": prompt
|
71 |
-
})
|
72 |
-
headers = {
|
73 |
-
"Authorization": f"Bearer {token}",
|
74 |
-
"Content-Type": "application/json",
|
75 |
-
"User-Agent": "PythonRawClient/1.0"
|
76 |
-
}
|
77 |
-
|
78 |
-
# === CONNECTION ===
|
79 |
-
context = ssl.create_default_context()
|
80 |
-
conn = http.client.HTTPSConnection(host, context=context)
|
81 |
-
|
82 |
-
# === RAW REQUEST ===
|
83 |
-
print("🔸 REQUEST LINE:")
|
84 |
-
print(f"POST {endpoint} HTTP/1.1")
|
85 |
-
print(f"Host: {host}")
|
86 |
-
for key, value in headers.items():
|
87 |
-
print(f"{key}: {value}")
|
88 |
-
print(f"\n{body}\n")
|
89 |
-
|
90 |
-
# Send request
|
91 |
-
conn.request("POST", endpoint, body=body, headers=headers)
|
92 |
-
|
93 |
-
# === RAW RESPONSE ===
|
94 |
-
response = conn.getresponse()
|
95 |
-
print("🔹 STATUS:", response.status, response.reason)
|
96 |
-
print("🔹 RESPONSE HEADERS:")
|
97 |
-
for hdr in response.getheaders():
|
98 |
-
print(f"{hdr[0]}: {hdr[1]}")
|
99 |
-
print("\n🔹 RESPONSE BODY (raw):")
|
100 |
-
raw = response.read()
|
101 |
-
try:
|
102 |
-
print(raw.decode("utf-8")[:1000]) # print first 1k chars
|
103 |
-
except UnicodeDecodeError:
|
104 |
-
print("[binary data]")
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
def query_model(model_name,prompt):
|
109 |
-
logs = []
|
110 |
-
img_out = None
|
111 |
-
|
112 |
-
host = "api-inference.huggingface.co"
|
113 |
-
endpoint = f"/models/{model_name}"
|
114 |
-
# Prepare request
|
115 |
-
body = json.dumps({"inputs": prompt})
|
116 |
-
headers = {
|
117 |
-
"Authorization": f"Bearer {token}",
|
118 |
-
"Content-Type": "application/json",
|
119 |
-
"User-Agent": "PythonRawClient/1.0"
|
120 |
-
}
|
121 |
-
|
122 |
-
# Connect
|
123 |
-
context = ssl.create_default_context()
|
124 |
-
conn = http.client.HTTPSConnection(host, context=context)
|
125 |
-
|
126 |
-
logs.append(f"📤 POST {endpoint}")
|
127 |
-
logs.append(f"Headers: {headers}")
|
128 |
-
logs.append(f"Body: {body}\n")
|
129 |
-
|
130 |
try:
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
logs.append(f"📥 Status: {response.status} {response.reason}")
|
136 |
-
logs.append("Headers:")
|
137 |
-
for k, v in response.getheaders():
|
138 |
-
logs.append(f"{k}: {v}")
|
139 |
-
|
140 |
-
raw = response.read()
|
141 |
-
|
142 |
-
try:
|
143 |
-
text = raw.decode("utf-8")
|
144 |
-
result = json.loads(text)
|
145 |
-
logs.append("\nBody:\n" + text[:1000])
|
146 |
-
except:
|
147 |
-
result = raw
|
148 |
-
logs.append("\n⚠️ Binary response.")
|
149 |
-
|
150 |
-
# === HANDLE RESPONSE ===
|
151 |
-
def show(img_bytes):
|
152 |
-
try:
|
153 |
-
img = Image.open(BytesIO(img_bytes))
|
154 |
-
return img
|
155 |
-
except Exception as e:
|
156 |
-
logs.append(f"❌ Failed to open image: {e}")
|
157 |
-
return None
|
158 |
-
|
159 |
-
if isinstance(result, dict):
|
160 |
-
if "image" in result:
|
161 |
-
logs.append("🧠 Found base64 image in 'image'")
|
162 |
-
return show(base64.b64decode(result["image"])), "\n".join(logs)
|
163 |
-
|
164 |
-
elif "url" in result or "image_url" in result:
|
165 |
-
url = result.get("url") or result.get("image_url")
|
166 |
-
logs.append(f"🌐 Found image URL: {url}")
|
167 |
-
r = requests.get(url)
|
168 |
-
return show(r.content), "\n".join(logs)
|
169 |
-
|
170 |
-
else:
|
171 |
-
logs.append("⚠️ No image found in response.")
|
172 |
-
return None, "\n".join(logs)
|
173 |
-
|
174 |
-
elif isinstance(result, bytes):
|
175 |
-
logs.append("🧾 Raw image bytes returned.")
|
176 |
-
return show(result), "\n".join(logs)
|
177 |
-
|
178 |
else:
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
return None, "\n".join(logs)
|
185 |
-
|
186 |
-
|
187 |
-
# === GRADIO UI ===
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
def query_model2(model_name, prompt):
|
192 |
-
logs = []
|
193 |
-
img_out = None
|
194 |
-
try:
|
195 |
-
model = gr.Interface.load(f"models/{model_name}", token=HF_TOKEN)
|
196 |
-
logs.append(f"Prompt: {prompt}")
|
197 |
-
response = model.predict(prompt)
|
198 |
-
logs.append(f"Model response: {response}")
|
199 |
-
def get_image_from_response(response):
|
200 |
-
if isinstance(response, dict):
|
201 |
-
if "image" in response:
|
202 |
-
img_data = base64.b64decode(response["image"])
|
203 |
-
img = Image.open(BytesIO(img_data))
|
204 |
-
return img
|
205 |
-
elif "url" in response or "image_url" in response:
|
206 |
-
url = response.get("url") or response.get("image_url")
|
207 |
-
img_data = requests.get(url).content
|
208 |
-
img = Image.open(BytesIO(img_data))
|
209 |
-
return img
|
210 |
-
elif isinstance(response, bytes):
|
211 |
-
img = Image.open(BytesIO(response))
|
212 |
-
return img
|
213 |
-
return None
|
214 |
-
img_out = get_image_from_response(response)
|
215 |
except Exception as e:
|
216 |
-
|
217 |
-
|
218 |
-
return img_out, "\n".join(logs)
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
|
223 |
-
#
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
match = re.search(pattern, log_message)
|
239 |
-
if match:
|
240 |
-
return match.group(1) # Return the current error code
|
241 |
-
return None # Return None if no match is found
|
242 |
-
def extract_model_name(self, log_message):
|
243 |
-
match = re.search(self.model_name_pattern, log_message)
|
244 |
-
if match:
|
245 |
-
return match.group(1) # Return the model name or identifier
|
246 |
-
return "Unknown model" # Return a default value if no model name is found
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
def debugon():
|
252 |
-
print(f"DEBUGGING MODE : ON ")
|
253 |
-
logging.basicConfig(level=logging.DEBUG, format='%(message)s')
|
254 |
-
error_handler = ErrorCodeLogHandler()
|
255 |
-
print(f"{error_handler}")
|
256 |
-
logging.getLogger().addHandler(error_handler)
|
257 |
-
def debugoff():
|
258 |
-
print(f"DEBUGGING MODE : OFF ")
|
259 |
-
logging.basicConfig(level=logging.WARNING, format='%(message)s')
|
260 |
-
error_handler = ErrorCodeLogHandler()
|
261 |
-
print(f"{error_handler}")
|
262 |
-
logging.getLogger().addHandler(error_handler)
|
263 |
-
def handle_debug_mode(selected_option):
|
264 |
-
if selected_option == "debug on":
|
265 |
-
debugon()
|
266 |
-
else:
|
267 |
-
debugoff()
|
268 |
-
|
269 |
-
|
270 |
-
|
271 |
-
def stop_all_tasks():
|
272 |
-
print("Stopping...")
|
273 |
-
stop_event.set()
|
274 |
-
|
275 |
-
|
276 |
-
|
277 |
-
with gr.Blocks(fill_width=True) as demo:
|
278 |
-
with gr.Tab(label="DEBUG"):
|
279 |
-
with gr.Row():
|
280 |
-
radio = gr.Radio(["debug on", "debug off"], value="debug off", label=" Debug mode: activated in output log", interactive=True)
|
281 |
-
radio.change(handle_debug_mode, radio, None)
|
282 |
-
|
283 |
-
with gr.Tab(str(num_models) + ' Models'):
|
284 |
-
with gr.Column(scale=2):
|
285 |
-
with gr.Group():
|
286 |
-
txt_input = gr.Textbox(label='Your prompt:', value=preSetPrompt, lines=3, autofocus=1)
|
287 |
-
neg_input = gr.Textbox(label='Negative prompt:', value=negPreSetPrompt, lines=1)
|
288 |
-
timeout = gr.Slider(label="Timeout (seconds)", minimum=5, maximum=300, value=120, step=1)
|
289 |
-
with gr.Accordion("Advanced", open=False, visible=True):
|
290 |
-
with gr.Row():
|
291 |
-
width = gr.Slider(label="Width", info="If 0, the default value is used.", maximum=1216, step=32, value=0)
|
292 |
-
height = gr.Slider(label="Height", info="If 0, the default value is used.", maximum=1216, step=32, value=0)
|
293 |
-
with gr.Row():
|
294 |
-
steps = gr.Slider(label="Number of inference steps", info="If 0, the default value is used.", maximum=100, step=1, value=0)
|
295 |
-
cfg = gr.Slider(label="Guidance scale", info="If 0, the default value is used.", maximum=30.0, step=0.1, value=0)
|
296 |
-
seed = gr.Slider(label="Seed", info="Randomize Seed if -1.", minimum=-1, maximum=MAX_SEED, step=1, value=-1)
|
297 |
-
seed_rand = gr.Button("Randomize Seed 🎲", size="sm", variant="secondary")
|
298 |
-
seed_rand.click(randomize_seed, None, [seed], queue=False)
|
299 |
-
with gr.Row():
|
300 |
-
gen_button = gr.Button(f'Generate up to {int(num_models)} images', variant='primary', scale=3, elem_classes=["butt"])
|
301 |
-
random_button = gr.Button(f'Randomize Models', variant='secondary', scale=1)
|
302 |
-
|
303 |
-
with gr.Column(scale=1):
|
304 |
-
with gr.Group():
|
305 |
-
with gr.Row():
|
306 |
-
output = [gr.Image(label=m, show_download_button=True, elem_classes=["image-monitor"],
|
307 |
-
interactive=False, width=112, height=112, show_share_button=False, format="png",
|
308 |
-
visible=True) for m in default_models]
|
309 |
-
current_models = [gr.Textbox(m, visible=False) for m in default_models]
|
310 |
-
|
311 |
-
#for m, o in zip(current_models, output):
|
312 |
-
# gen_event = gr.on(triggers=[gen_button.click, txt_input.submit], fn=gen_fn,
|
313 |
-
# inputs=[m, txt_input, neg_input, height, width, steps, cfg, seed], outputs=[o],
|
314 |
-
# concurrency_limit=None, queue=False)
|
315 |
-
for m, o in zip(current_models, output):
|
316 |
-
gen_button.click( fn=gen_fn, inputs=[m, txt_input, neg_input, height, width, steps, cfg, seed, timeout], outputs=[o],queue=False)
|
317 |
-
#concurrency_limit=None,
|
318 |
-
txt_input.submit( fn=gen_fn, inputs=[m, txt_input, neg_input, height, width, steps, cfg, seed, timeout], outputs=[o],queue=False)
|
319 |
-
|
320 |
-
with gr.Column(scale=4):
|
321 |
-
with gr.Accordion('Model selection'):
|
322 |
-
model_choice = gr.CheckboxGroup(models, label = f'Choose up to {int(num_models)} different models from the {len(models)} available!', value=models, interactive=True)
|
323 |
-
model_choice.change(update_imgbox, model_choice, output)
|
324 |
-
model_choice.change(extend_choices, model_choice, current_models)
|
325 |
-
random_button.click(random_choices, None, model_choice)
|
326 |
-
stop_button = gr.Button("Stop 🛑", variant="stop")
|
327 |
-
stop_button.click(
|
328 |
-
fn=stop_all_tasks,
|
329 |
-
inputs=[],
|
330 |
-
outputs=[]
|
331 |
-
)
|
332 |
-
|
333 |
-
demo.launch(show_api=True, max_threads=400)
|
334 |
-
|
335 |
-
|
336 |
-
'''
|
337 |
-
with gr.Blocks(fill_width=True) as demo:
|
338 |
-
with gr.Row():
|
339 |
-
gr.Markdown(f"# ({username}) you are logged in")
|
340 |
-
#model_selector = gr.CheckboxGroup(choices=model_ids,value=model_ids, label="your models", interactive=True, )
|
341 |
-
#output_box = gr.Textbox(lines=10, label="Selected Models")
|
342 |
-
#model_selector.change(fn=handle_model_selection, inputs=model_selector, outputs=output_box)
|
343 |
-
source_selector = gr.CheckboxGroup(choices=source_choices, label="Model Source", value=["Combined"], interactive=True)
|
344 |
-
|
345 |
-
output = gr.Textbox(label="Selected Model Summary")
|
346 |
-
with gr.Tab(str(num_models) + ' Models'):
|
347 |
-
with gr.Column(scale=2):
|
348 |
-
with gr.Group():
|
349 |
-
txt_input = gr.Textbox(label='Your prompt:', value=preSetPrompt, lines=3, autofocus=1)
|
350 |
-
with gr.Accordion("Advanced", open=False, visible=True):
|
351 |
-
with gr.Row():
|
352 |
-
neg_input = gr.Textbox(label='Negative prompt:', value=negPreSetPrompt, lines=1)
|
353 |
-
with gr.Row():
|
354 |
-
width = gr.Slider(label="Width", info="If 0, the default value is used.", maximum=1216, step=32, value=0)
|
355 |
-
height = gr.Slider(label="Height", info="If 0, the default value is used.", maximum=1216, step=32, value=0)
|
356 |
-
with gr.Row():
|
357 |
-
steps = gr.Slider(label="Number of inference steps", info="If 0, the default value is used.", maximum=100, step=1, value=0)
|
358 |
-
cfg = gr.Slider(label="Guidance scale", info="If 0, the default value is used.", maximum=30.0, step=0.1, value=0)
|
359 |
-
seed = gr.Slider(label="Seed", info="Randomize Seed if -1.", minimum=-1, maximum=MAX_SEED, step=1, value=-1)
|
360 |
-
seed_rand = gr.Button("Randomize Seed 🎲", size="sm", variant="secondary")
|
361 |
-
seed_rand.click(randomize_seed, None, [seed], queue=False)
|
362 |
-
with gr.Row():
|
363 |
-
gen_button = gr.Button(f'Generate up to {int(num_models)} images', variant='primary', scale=3, elem_classes=["butt"])
|
364 |
-
random_button = gr.Button(f'Randomize Models', variant='secondary', scale=1)
|
365 |
-
with gr.Column(scale=1):
|
366 |
-
with gr.Group():
|
367 |
-
with gr.Row():
|
368 |
-
output = [gr.Image(label=m, show_download_button=True, elem_classes=["image-monitor"],
|
369 |
-
interactive=False, width=112, height=112, show_share_button=False, format="png",
|
370 |
-
visible=True) for m in default_models]
|
371 |
-
current_models = [gr.Textbox(m, visible=False) for m in default_models]
|
372 |
-
for m, o in zip(current_models, output):
|
373 |
-
gen_event = gr.on(triggers=[gen_button.click, txt_input.submit], fn=gen_fn,
|
374 |
-
inputs=[m, txt_input, neg_input, height, width, steps, cfg, seed], outputs=[o],
|
375 |
-
concurrency_limit=None, queue=False)
|
376 |
-
with gr.Column(scale=4):
|
377 |
-
with gr.Accordion('Model selection'):
|
378 |
-
#model_choice = gr.CheckboxGroup(models, label = f'Choose up to {int(num_models)} different models from the {len(models)} available!', value=default_models, interactive=True)
|
379 |
-
#model_choice.change(update_imgbox, model_choice, output)
|
380 |
-
#model_choice.change(extend_choices, model_choice, current_models)
|
381 |
-
model_choice = gr.CheckboxGroup(choices=combined_models, label="Models", value=combined_models[:20], interactive=True)
|
382 |
-
source_selector.change(update_model_choice, source_selector, model_choice)
|
383 |
-
model_choice.change(handle_model_selection, model_choice, output)
|
384 |
-
model_choice.change(update_imgbox, model_choice, output)
|
385 |
-
model_choice.change(extend_choices, model_choice, current_models)
|
386 |
-
random_button.click(random_choices, None, model_choice)
|
387 |
-
|
388 |
-
'''
|
389 |
-
|
390 |
-
|
391 |
-
|
392 |
-
|
393 |
-
|
394 |
-
|
395 |
-
|
396 |
-
|
397 |
-
|
398 |
-
|
399 |
-
|
400 |
-
|
401 |
-
|
402 |
-
|
403 |
-
|
404 |
-
|
405 |
-
|
406 |
-
|
407 |
-
|
408 |
-
'''
|
409 |
-
|
410 |
-
# --- Step 2: Fetch user's Spaces
|
411 |
-
spaces = list(api.list_spaces(author=username, token=HF_TOKEN))
|
412 |
-
space_df = pd.DataFrame([{"Space Name": f"<a href='#' data-space='{space.id}'>{space.id.split('/')[-1]}</a>",
|
413 |
-
"Last Modified": space.lastModified,} for space in spaces])
|
414 |
-
|
415 |
-
def load_space_files(evt: gr.SelectData):
|
416 |
-
clicked_html = evt.value
|
417 |
-
space_id = clicked_html.split("data-space='")[1].split("'")[0]
|
418 |
-
files = api.list_repo_files(repo_id=space_id, repo_type="space", token=HF_TOKEN)
|
419 |
-
file_df = pd.DataFrame([{ "File": f"<a href='https://huggingface.co/spaces/{username}/{space_id.split('/')[-1]}/edit/main/{file}' target='_blank'>{file}</a>"
|
420 |
-
} for file in files])
|
421 |
-
return file_df
|
422 |
-
|
423 |
-
# --- Step 4: Build Gradio interface
|
424 |
-
gr.Markdown(f"# Hugging Face Spaces for `{username}`")
|
425 |
with gr.Row():
|
426 |
-
|
427 |
-
|
428 |
-
|
429 |
-
|
430 |
-
|
431 |
-
|
432 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
|
|
|
|
|
|
|
|
2 |
import os
|
3 |
+
from huggingface_hub import InferenceClient, list_models
|
4 |
+
from diffusers import StableDiffusionXLPipeline
|
5 |
+
import torch
|
6 |
+
from PIL import Image
|
7 |
+
import traceback
|
8 |
+
|
9 |
+
# Load token from env
|
10 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
11 |
+
USE_LOCAL = False # default mode
|
12 |
+
client_cache = {}
|
13 |
+
|
14 |
+
# Your models (replace with yours)
|
15 |
+
all_models = [
|
16 |
+
"stabilityai/stable-diffusion-xl-base-1.0",
|
17 |
+
"runwayml/stable-diffusion-v1-5",
|
18 |
+
"Uthar/John6666_epicrealism-xl-v8kiss-sdxl"
|
19 |
+
]
|
20 |
+
|
21 |
+
# Local model loading (simplified, for demo)
|
22 |
+
def load_local_pipeline(model_id):
|
23 |
+
pipe = StableDiffusionXLPipeline.from_pretrained(
|
24 |
+
model_id, torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32
|
25 |
+
)
|
26 |
+
return pipe.to("cuda" if torch.cuda.is_available() else "cpu")
|
27 |
+
|
28 |
+
# Main generation logic
|
29 |
+
def generate(model_id, prompt, use_local):
|
30 |
+
global client_cache
|
31 |
+
debug_log = ""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
32 |
try:
|
33 |
+
if use_local:
|
34 |
+
debug_log += f"🔧 Using local pipeline for: {model_id}\n"
|
35 |
+
pipe = load_local_pipeline(model_id)
|
36 |
+
image = pipe(prompt).images[0]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
37 |
else:
|
38 |
+
debug_log += f"🌐 Using InferenceClient for: {model_id}\n"
|
39 |
+
if model_id not in client_cache:
|
40 |
+
client_cache[model_id] = InferenceClient(model=model_id, token=HF_TOKEN)
|
41 |
+
image = client_cache[model_id].text_to_image(prompt)
|
42 |
+
return image, debug_log + "\n✅ Success."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
43 |
except Exception as e:
|
44 |
+
error_msg = traceback.format_exc()
|
45 |
+
return None, debug_log + f"\n❌ Error:\n{error_msg}"
|
|
|
|
|
|
|
|
|
46 |
|
47 |
+
# Model API self-check
|
48 |
+
def check_model_access(models):
|
49 |
+
results = ""
|
50 |
+
for model in models:
|
51 |
+
try:
|
52 |
+
client = InferenceClient(model=model, token=HF_TOKEN)
|
53 |
+
_ = client.text_to_image("test prompt", max_retry=1)
|
54 |
+
results += f"✅ {model} is working.\n"
|
55 |
+
except Exception as e:
|
56 |
+
results += f"❌ {model} failed: {str(e).splitlines()[0]}\n"
|
57 |
+
return results
|
58 |
+
|
59 |
+
# Gradio UI
|
60 |
+
with gr.Blocks() as demo:
|
61 |
+
gr.Markdown("# 🧪 Stable Diffusion API Tester")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
62 |
with gr.Row():
|
63 |
+
model = gr.Dropdown(choices=all_models, label="Model", value=all_models[0])
|
64 |
+
use_local = gr.Checkbox(label="Use Local Diffusers Instead of API", value=USE_LOCAL)
|
65 |
+
prompt = gr.Textbox(label="Prompt", value="a cyberpunk cat playing guitar in Tokyo")
|
66 |
+
generate_btn = gr.Button("Generate")
|
67 |
+
image_out = gr.Image(label="Generated Image")
|
68 |
+
debug_out = gr.Textbox(label="Debug Output", lines=10)
|
69 |
+
with gr.Accordion("Self-Check: API Model Access", open=False):
|
70 |
+
check_btn = gr.Button("Check All Models")
|
71 |
+
check_results = gr.Textbox(label="Model API Status", lines=10)
|
72 |
+
|
73 |
+
generate_btn.click(generate, inputs=[model, prompt, use_local], outputs=[image_out, debug_out])
|
74 |
+
check_btn.click(check_model_access, inputs=[gr.State(all_models)], outputs=[check_results])
|
75 |
+
|
76 |
+
demo.launch()
|