Spaces:
Running
Running
refactor(core): modularize application structure
Browse files- [remove] Remove core chat/image logic and direct Gradio UI definitions (app.py:chat_respond, generate_image, validate_dimensions, handle_chat_submit, on_generate_image)
- [refactor] Refactor app.py to orchestrate the application via create_app(), connecting modular UI and logic handlers (app.py:create_app(), 27-38)
- [add] Introduce chat and image handler files to encapsulate chat and image generation logic, integrating utils helpers (chat_handler.py:chat_respond(), image_handler.py:generate_image())
- [add] Create modular Gradio UI definition (ui_components.py)
- [add] Add utility file to centralize helper functions and configuration constants (utils.py)
- app.py +30 -494
- chat_handler.py +132 -0
- image_handler.py +124 -0
- ui_components.py +291 -0
- utils.py +116 -0
app.py
CHANGED
|
@@ -1,507 +1,43 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
from hf_token_utils import get_proxy_token, report_token_status
|
| 6 |
-
import PIL.Image
|
| 7 |
-
import io
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
def chat_respond(
|
| 11 |
-
message,
|
| 12 |
-
history: list[dict[str, str]],
|
| 13 |
-
system_message,
|
| 14 |
-
model_name,
|
| 15 |
-
max_tokens,
|
| 16 |
-
temperature,
|
| 17 |
-
top_p,
|
| 18 |
-
):
|
| 19 |
-
"""
|
| 20 |
-
Chat completion function using HF-Inferoxy token management.
|
| 21 |
-
"""
|
| 22 |
-
# Get proxy API key from environment variable (set in HuggingFace Space secrets)
|
| 23 |
-
proxy_api_key = os.getenv("PROXY_KEY")
|
| 24 |
-
if not proxy_api_key:
|
| 25 |
-
yield "β Error: PROXY_KEY not found in environment variables. Please set it in your HuggingFace Space secrets."
|
| 26 |
-
return
|
| 27 |
-
|
| 28 |
-
try:
|
| 29 |
-
# Get token from HF-Inferoxy proxy server
|
| 30 |
-
print(f"π Chat: Requesting token from proxy...")
|
| 31 |
-
token, token_id = get_proxy_token(api_key=proxy_api_key)
|
| 32 |
-
print(f"β
Chat: Got token: {token_id}")
|
| 33 |
-
|
| 34 |
-
# Parse model name and provider if specified
|
| 35 |
-
if ":" in model_name:
|
| 36 |
-
model, provider = model_name.split(":", 1)
|
| 37 |
-
else:
|
| 38 |
-
model = model_name
|
| 39 |
-
provider = None
|
| 40 |
-
|
| 41 |
-
print(f"π€ Chat: Using model='{model}', provider='{provider if provider else 'auto'}'")
|
| 42 |
-
|
| 43 |
-
# Prepare messages first
|
| 44 |
-
messages = [{"role": "system", "content": system_message}]
|
| 45 |
-
messages.extend(history)
|
| 46 |
-
messages.append({"role": "user", "content": message})
|
| 47 |
-
|
| 48 |
-
print(f"π¬ Chat: Prepared {len(messages)} messages, creating client...")
|
| 49 |
-
|
| 50 |
-
# Create client with provider (auto if none specified) and always pass model
|
| 51 |
-
client = InferenceClient(
|
| 52 |
-
provider=provider if provider else "auto",
|
| 53 |
-
api_key=token
|
| 54 |
-
)
|
| 55 |
-
|
| 56 |
-
print(f"π Chat: Client created, starting inference...")
|
| 57 |
-
|
| 58 |
-
chat_completion_kwargs = {
|
| 59 |
-
"model": model,
|
| 60 |
-
"messages": messages,
|
| 61 |
-
"max_tokens": max_tokens,
|
| 62 |
-
"stream": True,
|
| 63 |
-
"temperature": temperature,
|
| 64 |
-
"top_p": top_p,
|
| 65 |
-
}
|
| 66 |
-
|
| 67 |
-
response = ""
|
| 68 |
-
|
| 69 |
-
print(f"π‘ Chat: Making streaming request...")
|
| 70 |
-
stream = client.chat_completion(**chat_completion_kwargs)
|
| 71 |
-
print(f"π Chat: Got stream, starting to iterate...")
|
| 72 |
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
report_token_status(token_id, "success", api_key=proxy_api_key)
|
| 84 |
-
|
| 85 |
-
except HfHubHTTPError as e:
|
| 86 |
-
# Report HF Hub errors
|
| 87 |
-
if 'token_id' in locals():
|
| 88 |
-
report_token_status(token_id, "error", str(e), api_key=proxy_api_key)
|
| 89 |
-
yield f"β HuggingFace API Error: {str(e)}"
|
| 90 |
-
|
| 91 |
-
except Exception as e:
|
| 92 |
-
# Report other errors
|
| 93 |
-
if 'token_id' in locals():
|
| 94 |
-
report_token_status(token_id, "error", str(e), api_key=proxy_api_key)
|
| 95 |
-
yield f"β Unexpected Error: {str(e)}"
|
| 96 |
|
| 97 |
|
| 98 |
-
def
|
| 99 |
-
|
| 100 |
-
model_name: str,
|
| 101 |
-
provider: str,
|
| 102 |
-
negative_prompt: str = "",
|
| 103 |
-
width: int = 1024,
|
| 104 |
-
height: int = 1024,
|
| 105 |
-
num_inference_steps: int = 20,
|
| 106 |
-
guidance_scale: float = 7.5,
|
| 107 |
-
seed: int = -1,
|
| 108 |
-
):
|
| 109 |
-
"""
|
| 110 |
-
Generate an image using the specified model and provider through HF-Inferoxy.
|
| 111 |
-
"""
|
| 112 |
-
# Get proxy API key from environment variable (set in HuggingFace Space secrets)
|
| 113 |
-
proxy_api_key = os.getenv("PROXY_KEY")
|
| 114 |
-
if not proxy_api_key:
|
| 115 |
-
return None, "β Error: PROXY_KEY not found in environment variables. Please set it in your HuggingFace Space secrets."
|
| 116 |
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
print(f"π Image: Requesting token from proxy...")
|
| 120 |
-
token, token_id = get_proxy_token(api_key=proxy_api_key)
|
| 121 |
-
print(f"β
Image: Got token: {token_id}")
|
| 122 |
-
|
| 123 |
-
print(f"π¨ Image: Using model='{model_name}', provider='{provider}'")
|
| 124 |
-
|
| 125 |
-
# Create client with specified provider
|
| 126 |
-
client = InferenceClient(
|
| 127 |
-
provider=provider,
|
| 128 |
-
api_key=token
|
| 129 |
-
)
|
| 130 |
-
|
| 131 |
-
print(f"π Image: Client created, preparing generation params...")
|
| 132 |
-
|
| 133 |
-
# Prepare generation parameters
|
| 134 |
-
generation_params = {
|
| 135 |
-
"model": model_name,
|
| 136 |
-
"prompt": prompt,
|
| 137 |
-
"width": width,
|
| 138 |
-
"height": height,
|
| 139 |
-
"num_inference_steps": num_inference_steps,
|
| 140 |
-
"guidance_scale": guidance_scale,
|
| 141 |
-
}
|
| 142 |
-
|
| 143 |
-
# Add optional parameters if provided
|
| 144 |
-
if negative_prompt:
|
| 145 |
-
generation_params["negative_prompt"] = negative_prompt
|
| 146 |
-
if seed != -1:
|
| 147 |
-
generation_params["seed"] = seed
|
| 148 |
-
|
| 149 |
-
print(f"π Image: Dimensions: {width}x{height}, steps: {num_inference_steps}, guidance: {guidance_scale}")
|
| 150 |
-
print(f"π‘ Image: Making generation request...")
|
| 151 |
-
|
| 152 |
-
# Generate image
|
| 153 |
-
image = client.text_to_image(**generation_params)
|
| 154 |
|
| 155 |
-
|
|
|
|
| 156 |
|
| 157 |
-
|
| 158 |
-
report_token_status(token_id, "success", api_key=proxy_api_key)
|
| 159 |
-
|
| 160 |
-
return image, f"β
Image generated successfully using {model_name} on {provider}!"
|
| 161 |
-
|
| 162 |
-
except HfHubHTTPError as e:
|
| 163 |
-
# Report HF Hub errors
|
| 164 |
-
if 'token_id' in locals():
|
| 165 |
-
report_token_status(token_id, "error", str(e), api_key=proxy_api_key)
|
| 166 |
-
return None, f"β HuggingFace API Error: {str(e)}"
|
| 167 |
-
|
| 168 |
-
except Exception as e:
|
| 169 |
-
# Report other errors
|
| 170 |
-
if 'token_id' in locals():
|
| 171 |
-
report_token_status(token_id, "error", str(e), api_key=proxy_api_key)
|
| 172 |
-
return None, f"β Unexpected Error: {str(e)}"
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
def validate_dimensions(width, height):
|
| 176 |
-
"""Validate that dimensions are divisible by 8 (required by most diffusion models)"""
|
| 177 |
-
if width % 8 != 0 or height % 8 != 0:
|
| 178 |
-
return False, "Width and height must be divisible by 8"
|
| 179 |
-
return True, ""
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
# Create the main Gradio interface with tabs
|
| 183 |
-
with gr.Blocks(title="HF-Inferoxy AI Hub", theme=gr.themes.Soft()) as demo:
|
| 184 |
-
|
| 185 |
-
# Main header
|
| 186 |
-
gr.Markdown("""
|
| 187 |
-
# π HF-Inferoxy AI Hub
|
| 188 |
-
|
| 189 |
-
A comprehensive AI platform combining chat and image generation capabilities with intelligent token management through HF-Inferoxy.
|
| 190 |
-
|
| 191 |
-
**Features:**
|
| 192 |
-
- π¬ **Smart Chat**: Conversational AI with streaming responses
|
| 193 |
-
- π¨ **Image Generation**: Text-to-image creation with multiple providers
|
| 194 |
-
- π **Intelligent Token Management**: Automatic token rotation and error handling
|
| 195 |
-
- π **Multi-Provider Support**: Works with HF Inference, Cerebras, Cohere, Groq, Together, Fal.ai, and more
|
| 196 |
-
""")
|
| 197 |
-
|
| 198 |
-
with gr.Tabs() as tabs:
|
| 199 |
-
|
| 200 |
-
# ==================== CHAT TAB ====================
|
| 201 |
-
with gr.Tab("π¬ Chat Assistant", id="chat"):
|
| 202 |
-
# Chat interface at the top - most prominent
|
| 203 |
-
chatbot_display = gr.Chatbot(
|
| 204 |
-
label="Chat",
|
| 205 |
-
type="messages",
|
| 206 |
-
height=800,
|
| 207 |
-
show_copy_button=True
|
| 208 |
-
)
|
| 209 |
|
| 210 |
-
# Chat
|
| 211 |
-
|
| 212 |
-
chat_input = gr.Textbox(
|
| 213 |
-
placeholder="Type your message here...",
|
| 214 |
-
label="Message",
|
| 215 |
-
scale=4,
|
| 216 |
-
container=False
|
| 217 |
-
)
|
| 218 |
-
chat_submit = gr.Button("Send", variant="primary", scale=1)
|
| 219 |
|
| 220 |
-
#
|
| 221 |
-
|
| 222 |
-
with gr.Column(scale=1):
|
| 223 |
-
chat_model_name = gr.Textbox(
|
| 224 |
-
value="openai/gpt-oss-20b",
|
| 225 |
-
label="Model Name",
|
| 226 |
-
placeholder="e.g., openai/gpt-oss-20b or openai/gpt-oss-20b:fireworks-ai"
|
| 227 |
-
)
|
| 228 |
-
chat_system_message = gr.Textbox(
|
| 229 |
-
value="You are a helpful and friendly AI assistant. Provide clear, accurate, and helpful responses.",
|
| 230 |
-
label="System Message",
|
| 231 |
-
lines=2,
|
| 232 |
-
placeholder="Define the assistant's personality and behavior..."
|
| 233 |
-
)
|
| 234 |
-
|
| 235 |
-
with gr.Column(scale=1):
|
| 236 |
-
chat_max_tokens = gr.Slider(
|
| 237 |
-
minimum=1, maximum=4096, value=1024, step=1,
|
| 238 |
-
label="Max New Tokens"
|
| 239 |
-
)
|
| 240 |
-
chat_temperature = gr.Slider(
|
| 241 |
-
minimum=0.1, maximum=2.0, value=0.7, step=0.1,
|
| 242 |
-
label="Temperature"
|
| 243 |
-
)
|
| 244 |
-
chat_top_p = gr.Slider(
|
| 245 |
-
minimum=0.1, maximum=1.0, value=0.95, step=0.05,
|
| 246 |
-
label="Top-p (nucleus sampling)"
|
| 247 |
-
)
|
| 248 |
-
|
| 249 |
-
# Configuration tips below the chat
|
| 250 |
-
with gr.Row():
|
| 251 |
-
with gr.Column():
|
| 252 |
-
gr.Markdown("""
|
| 253 |
-
### π‘ Chat Tips
|
| 254 |
-
|
| 255 |
-
**Model Format:**
|
| 256 |
-
- Single model: `openai/gpt-oss-20b` (uses auto provider)
|
| 257 |
-
- With provider: `openai/gpt-oss-20b:fireworks-ai`
|
| 258 |
-
|
| 259 |
-
**Popular Models:**
|
| 260 |
-
- `openai/gpt-oss-20b` - Fast general purpose
|
| 261 |
-
- `meta-llama/Llama-2-7b-chat-hf` - Chat optimized
|
| 262 |
-
- `microsoft/DialoGPT-medium` - Conversation
|
| 263 |
-
- `google/flan-t5-base` - Instruction following
|
| 264 |
-
""")
|
| 265 |
-
|
| 266 |
-
with gr.Column():
|
| 267 |
-
gr.Markdown("""
|
| 268 |
-
### π Popular Providers
|
| 269 |
-
|
| 270 |
-
- **auto** - Let HF choose best provider (default)
|
| 271 |
-
- **fireworks-ai** - Fast and reliable
|
| 272 |
-
- **cerebras** - High performance
|
| 273 |
-
- **groq** - Ultra-fast inference
|
| 274 |
-
- **together** - Wide model support
|
| 275 |
-
- **cohere** - Advanced language models
|
| 276 |
-
|
| 277 |
-
**Examples:**
|
| 278 |
-
- `openai/gpt-oss-20b` (auto provider)
|
| 279 |
-
- `openai/gpt-oss-20b:fireworks-ai` (specific provider)
|
| 280 |
-
""")
|
| 281 |
-
|
| 282 |
-
# Chat functionality
|
| 283 |
-
def handle_chat_submit(message, history, system_msg, model_name, max_tokens, temperature, top_p):
|
| 284 |
-
if not message.strip():
|
| 285 |
-
return history, ""
|
| 286 |
-
|
| 287 |
-
# Add user message to history
|
| 288 |
-
history = history + [{"role": "user", "content": message}]
|
| 289 |
-
|
| 290 |
-
# Generate response
|
| 291 |
-
response_generator = chat_respond(
|
| 292 |
-
message,
|
| 293 |
-
history[:-1], # Don't include the current message in history for the function
|
| 294 |
-
system_msg,
|
| 295 |
-
model_name,
|
| 296 |
-
max_tokens,
|
| 297 |
-
temperature,
|
| 298 |
-
top_p
|
| 299 |
-
)
|
| 300 |
-
|
| 301 |
-
# Get the final response
|
| 302 |
-
assistant_response = ""
|
| 303 |
-
for partial_response in response_generator:
|
| 304 |
-
assistant_response = partial_response
|
| 305 |
-
|
| 306 |
-
# Add assistant response to history
|
| 307 |
-
history = history + [{"role": "assistant", "content": assistant_response}]
|
| 308 |
-
|
| 309 |
-
return history, ""
|
| 310 |
-
|
| 311 |
-
# Connect chat events
|
| 312 |
-
chat_submit.click(
|
| 313 |
-
fn=handle_chat_submit,
|
| 314 |
-
inputs=[chat_input, chatbot_display, chat_system_message, chat_model_name,
|
| 315 |
-
chat_max_tokens, chat_temperature, chat_top_p],
|
| 316 |
-
outputs=[chatbot_display, chat_input]
|
| 317 |
-
)
|
| 318 |
-
|
| 319 |
-
chat_input.submit(
|
| 320 |
-
fn=handle_chat_submit,
|
| 321 |
-
inputs=[chat_input, chatbot_display, chat_system_message, chat_model_name,
|
| 322 |
-
chat_max_tokens, chat_temperature, chat_top_p],
|
| 323 |
-
outputs=[chatbot_display, chat_input]
|
| 324 |
-
)
|
| 325 |
-
|
| 326 |
-
# ==================== IMAGE GENERATION TAB ====================
|
| 327 |
-
with gr.Tab("π¨ Image Generator", id="image"):
|
| 328 |
-
with gr.Row():
|
| 329 |
-
with gr.Column(scale=2):
|
| 330 |
-
# Image output
|
| 331 |
-
output_image = gr.Image(
|
| 332 |
-
label="Generated Image",
|
| 333 |
-
type="pil",
|
| 334 |
-
height=600,
|
| 335 |
-
show_download_button=True
|
| 336 |
-
)
|
| 337 |
-
status_text = gr.Textbox(
|
| 338 |
-
label="Generation Status",
|
| 339 |
-
interactive=False,
|
| 340 |
-
lines=2
|
| 341 |
-
)
|
| 342 |
-
|
| 343 |
-
with gr.Column(scale=1):
|
| 344 |
-
# Model and provider inputs
|
| 345 |
-
with gr.Group():
|
| 346 |
-
gr.Markdown("**π€ Model & Provider**")
|
| 347 |
-
img_model_name = gr.Textbox(
|
| 348 |
-
value="Qwen/Qwen-Image",
|
| 349 |
-
label="Model Name",
|
| 350 |
-
placeholder="e.g., Qwen/Qwen-Image or stabilityai/stable-diffusion-xl-base-1.0"
|
| 351 |
-
)
|
| 352 |
-
img_provider = gr.Dropdown(
|
| 353 |
-
choices=["hf-inference", "fal-ai", "nebius", "nscale", "replicate", "together"],
|
| 354 |
-
value="fal-ai",
|
| 355 |
-
label="Provider",
|
| 356 |
-
interactive=True
|
| 357 |
-
)
|
| 358 |
-
|
| 359 |
-
# Generation parameters
|
| 360 |
-
with gr.Group():
|
| 361 |
-
gr.Markdown("**π Prompts**")
|
| 362 |
-
img_prompt = gr.Textbox(
|
| 363 |
-
value="A beautiful landscape with mountains and a lake at sunset, photorealistic, 8k, highly detailed",
|
| 364 |
-
label="Prompt",
|
| 365 |
-
lines=3,
|
| 366 |
-
placeholder="Describe the image you want to generate..."
|
| 367 |
-
)
|
| 368 |
-
img_negative_prompt = gr.Textbox(
|
| 369 |
-
value="blurry, low quality, distorted, deformed, ugly, bad anatomy",
|
| 370 |
-
label="Negative Prompt",
|
| 371 |
-
lines=2,
|
| 372 |
-
placeholder="Describe what you DON'T want in the image..."
|
| 373 |
-
)
|
| 374 |
-
|
| 375 |
-
with gr.Group():
|
| 376 |
-
gr.Markdown("**βοΈ Generation Settings**")
|
| 377 |
-
with gr.Row():
|
| 378 |
-
img_width = gr.Slider(
|
| 379 |
-
minimum=256, maximum=2048, value=1024, step=64,
|
| 380 |
-
label="Width", info="Must be divisible by 8"
|
| 381 |
-
)
|
| 382 |
-
img_height = gr.Slider(
|
| 383 |
-
minimum=256, maximum=2048, value=1024, step=64,
|
| 384 |
-
label="Height", info="Must be divisible by 8"
|
| 385 |
-
)
|
| 386 |
-
|
| 387 |
-
with gr.Row():
|
| 388 |
-
img_steps = gr.Slider(
|
| 389 |
-
minimum=10, maximum=100, value=20, step=1,
|
| 390 |
-
label="Inference Steps", info="More steps = better quality"
|
| 391 |
-
)
|
| 392 |
-
img_guidance = gr.Slider(
|
| 393 |
-
minimum=1.0, maximum=20.0, value=7.5, step=0.5,
|
| 394 |
-
label="Guidance Scale", info="How closely to follow prompt"
|
| 395 |
-
)
|
| 396 |
-
|
| 397 |
-
img_seed = gr.Slider(
|
| 398 |
-
minimum=-1, maximum=999999, value=-1, step=1,
|
| 399 |
-
label="Seed", info="-1 for random"
|
| 400 |
-
)
|
| 401 |
-
|
| 402 |
-
# Generate button
|
| 403 |
-
generate_btn = gr.Button(
|
| 404 |
-
"π¨ Generate Image",
|
| 405 |
-
variant="primary",
|
| 406 |
-
size="lg",
|
| 407 |
-
scale=2
|
| 408 |
-
)
|
| 409 |
-
|
| 410 |
-
# Quick model presets
|
| 411 |
-
with gr.Group():
|
| 412 |
-
gr.Markdown("**π― Popular Presets**")
|
| 413 |
-
preset_buttons = []
|
| 414 |
-
presets = [
|
| 415 |
-
("Qwen (Fal.ai)", "Qwen/Qwen-Image", "fal-ai"),
|
| 416 |
-
("Qwen (Replicate)", "Qwen/Qwen-Image", "replicate"),
|
| 417 |
-
("FLUX.1 (Nebius)", "black-forest-labs/FLUX.1-dev", "nebius"),
|
| 418 |
-
("SDXL (HF)", "stabilityai/stable-diffusion-xl-base-1.0", "hf-inference"),
|
| 419 |
-
]
|
| 420 |
-
|
| 421 |
-
for name, model, provider in presets:
|
| 422 |
-
btn = gr.Button(name, size="sm")
|
| 423 |
-
btn.click(
|
| 424 |
-
lambda m=model, p=provider: (m, p),
|
| 425 |
-
outputs=[img_model_name, img_provider]
|
| 426 |
-
)
|
| 427 |
-
|
| 428 |
-
# Examples for image generation
|
| 429 |
-
with gr.Group():
|
| 430 |
-
gr.Markdown("**π Example Prompts**")
|
| 431 |
-
img_examples = gr.Examples(
|
| 432 |
-
examples=[
|
| 433 |
-
["A majestic dragon flying over a medieval castle, epic fantasy art, detailed, 8k"],
|
| 434 |
-
["A serene Japanese garden with cherry blossoms, zen atmosphere, peaceful, high quality"],
|
| 435 |
-
["A futuristic cityscape with flying cars and neon lights, cyberpunk style, cinematic"],
|
| 436 |
-
["A cute robot cat playing with yarn, adorable, cartoon style, vibrant colors"],
|
| 437 |
-
["A magical forest with glowing mushrooms and fairy lights, fantasy, ethereal beauty"],
|
| 438 |
-
["Portrait of a wise old wizard with flowing robes, magical aura, fantasy character art"],
|
| 439 |
-
["A cozy coffee shop on a rainy day, warm lighting, peaceful atmosphere, detailed"],
|
| 440 |
-
["An astronaut floating in space with Earth in background, photorealistic, stunning"]
|
| 441 |
-
],
|
| 442 |
-
inputs=img_prompt
|
| 443 |
-
)
|
| 444 |
-
|
| 445 |
-
# Event handlers for image generation
|
| 446 |
-
def on_generate_image(prompt_val, model_val, provider_val, negative_prompt_val, width_val, height_val, steps_val, guidance_val, seed_val):
|
| 447 |
-
# Validate dimensions
|
| 448 |
-
is_valid, error_msg = validate_dimensions(width_val, height_val)
|
| 449 |
-
if not is_valid:
|
| 450 |
-
return None, f"β Validation Error: {error_msg}"
|
| 451 |
|
| 452 |
-
#
|
| 453 |
-
|
| 454 |
-
prompt=prompt_val,
|
| 455 |
-
model_name=model_val,
|
| 456 |
-
provider=provider_val,
|
| 457 |
-
negative_prompt=negative_prompt_val,
|
| 458 |
-
width=width_val,
|
| 459 |
-
height=height_val,
|
| 460 |
-
num_inference_steps=steps_val,
|
| 461 |
-
guidance_scale=guidance_val,
|
| 462 |
-
seed=seed_val
|
| 463 |
-
)
|
| 464 |
-
|
| 465 |
-
# Connect image generation events
|
| 466 |
-
generate_btn.click(
|
| 467 |
-
fn=on_generate_image,
|
| 468 |
-
inputs=[
|
| 469 |
-
img_prompt, img_model_name, img_provider, img_negative_prompt,
|
| 470 |
-
img_width, img_height, img_steps, img_guidance, img_seed
|
| 471 |
-
],
|
| 472 |
-
outputs=[output_image, status_text]
|
| 473 |
-
)
|
| 474 |
-
|
| 475 |
-
# Footer with helpful information
|
| 476 |
-
gr.Markdown("""
|
| 477 |
-
---
|
| 478 |
-
### π How to Use
|
| 479 |
-
|
| 480 |
-
**Chat Tab:**
|
| 481 |
-
- Enter your message and customize the AI's behavior with system messages
|
| 482 |
-
- Choose models and providers using the format `model:provider`
|
| 483 |
-
- Adjust temperature for creativity and top-p for response diversity
|
| 484 |
-
|
| 485 |
-
**Image Tab:**
|
| 486 |
-
- Write detailed prompts describing your desired image
|
| 487 |
-
- Use negative prompts to avoid unwanted elements
|
| 488 |
-
- Experiment with different models and providers for varied styles
|
| 489 |
-
- Higher inference steps = better quality but slower generation
|
| 490 |
-
|
| 491 |
-
**Supported Providers:**
|
| 492 |
-
- **fal-ai**: High-quality image generation (default for images)
|
| 493 |
-
- **hf-inference**: Core API with comprehensive model support
|
| 494 |
-
- **cerebras**: High-performance inference
|
| 495 |
-
- **cohere**: Advanced language models with multilingual support
|
| 496 |
-
- **groq**: Ultra-fast inference, optimized for speed
|
| 497 |
-
- **together**: Collaborative AI hosting, wide model support
|
| 498 |
-
- **nebius**: Cloud-native services with enterprise features
|
| 499 |
-
- **nscale**: Optimized inference performance
|
| 500 |
-
- **replicate**: Collaborative AI hosting
|
| 501 |
|
| 502 |
-
|
| 503 |
-
""")
|
| 504 |
|
| 505 |
|
| 506 |
if __name__ == "__main__":
|
| 507 |
-
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
HF-Inferoxy AI Hub - Main application entry point.
|
| 3 |
+
A comprehensive AI platform with chat and image generation capabilities.
|
| 4 |
+
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
+
import gradio as gr
|
| 7 |
+
from chat_handler import handle_chat_submit
|
| 8 |
+
from image_handler import handle_image_generation
|
| 9 |
+
from ui_components import (
|
| 10 |
+
create_main_header,
|
| 11 |
+
create_chat_tab,
|
| 12 |
+
create_image_tab,
|
| 13 |
+
create_footer
|
| 14 |
+
)
|
| 15 |
+
from utils import get_gradio_theme
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
|
| 18 |
+
def create_app():
|
| 19 |
+
"""Create and configure the main Gradio application."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
+
# Create the main Gradio interface with tabs
|
| 22 |
+
with gr.Blocks(title="HF-Inferoxy AI Hub", theme=get_gradio_theme()) as demo:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
+
# Main header
|
| 25 |
+
create_main_header()
|
| 26 |
|
| 27 |
+
with gr.Tabs() as tabs:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
+
# Chat tab
|
| 30 |
+
create_chat_tab(handle_chat_submit)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
+
# Image generation tab
|
| 33 |
+
create_image_tab(handle_image_generation)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
+
# Footer with helpful information
|
| 36 |
+
create_footer()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
+
return demo
|
|
|
|
| 39 |
|
| 40 |
|
| 41 |
if __name__ == "__main__":
|
| 42 |
+
app = create_app()
|
| 43 |
+
app.launch()
|
chat_handler.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Chat functionality handler for HF-Inferoxy AI Hub.
|
| 3 |
+
Handles chat completion requests with streaming responses.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
from huggingface_hub import InferenceClient
|
| 8 |
+
from huggingface_hub.errors import HfHubHTTPError
|
| 9 |
+
from hf_token_utils import get_proxy_token, report_token_status
|
| 10 |
+
from utils import (
|
| 11 |
+
validate_proxy_key,
|
| 12 |
+
parse_model_and_provider,
|
| 13 |
+
format_error_message
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def chat_respond(
|
| 18 |
+
message,
|
| 19 |
+
history: list[dict[str, str]],
|
| 20 |
+
system_message,
|
| 21 |
+
model_name,
|
| 22 |
+
max_tokens,
|
| 23 |
+
temperature,
|
| 24 |
+
top_p,
|
| 25 |
+
):
|
| 26 |
+
"""
|
| 27 |
+
Chat completion function using HF-Inferoxy token management.
|
| 28 |
+
"""
|
| 29 |
+
# Validate proxy API key
|
| 30 |
+
is_valid, error_msg = validate_proxy_key()
|
| 31 |
+
if not is_valid:
|
| 32 |
+
yield error_msg
|
| 33 |
+
return
|
| 34 |
+
|
| 35 |
+
proxy_api_key = os.getenv("PROXY_KEY")
|
| 36 |
+
|
| 37 |
+
try:
|
| 38 |
+
# Get token from HF-Inferoxy proxy server
|
| 39 |
+
print(f"π Chat: Requesting token from proxy...")
|
| 40 |
+
token, token_id = get_proxy_token(api_key=proxy_api_key)
|
| 41 |
+
print(f"β
Chat: Got token: {token_id}")
|
| 42 |
+
|
| 43 |
+
# Parse model name and provider if specified
|
| 44 |
+
model, provider = parse_model_and_provider(model_name)
|
| 45 |
+
|
| 46 |
+
print(f"π€ Chat: Using model='{model}', provider='{provider if provider else 'auto'}'")
|
| 47 |
+
|
| 48 |
+
# Prepare messages first
|
| 49 |
+
messages = [{"role": "system", "content": system_message}]
|
| 50 |
+
messages.extend(history)
|
| 51 |
+
messages.append({"role": "user", "content": message})
|
| 52 |
+
|
| 53 |
+
print(f"π¬ Chat: Prepared {len(messages)} messages, creating client...")
|
| 54 |
+
|
| 55 |
+
# Create client with provider (auto if none specified) and always pass model
|
| 56 |
+
client = InferenceClient(
|
| 57 |
+
provider=provider if provider else "auto",
|
| 58 |
+
api_key=token
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
print(f"π Chat: Client created, starting inference...")
|
| 62 |
+
|
| 63 |
+
chat_completion_kwargs = {
|
| 64 |
+
"model": model,
|
| 65 |
+
"messages": messages,
|
| 66 |
+
"max_tokens": max_tokens,
|
| 67 |
+
"stream": True,
|
| 68 |
+
"temperature": temperature,
|
| 69 |
+
"top_p": top_p,
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
response = ""
|
| 73 |
+
|
| 74 |
+
print(f"π‘ Chat: Making streaming request...")
|
| 75 |
+
stream = client.chat_completion(**chat_completion_kwargs)
|
| 76 |
+
print(f"π Chat: Got stream, starting to iterate...")
|
| 77 |
+
|
| 78 |
+
for message in stream:
|
| 79 |
+
choices = message.choices
|
| 80 |
+
token_content = ""
|
| 81 |
+
if len(choices) and choices[0].delta.content:
|
| 82 |
+
token_content = choices[0].delta.content
|
| 83 |
+
|
| 84 |
+
response += token_content
|
| 85 |
+
yield response
|
| 86 |
+
|
| 87 |
+
# Report successful token usage
|
| 88 |
+
report_token_status(token_id, "success", api_key=proxy_api_key)
|
| 89 |
+
|
| 90 |
+
except HfHubHTTPError as e:
|
| 91 |
+
# Report HF Hub errors
|
| 92 |
+
if 'token_id' in locals():
|
| 93 |
+
report_token_status(token_id, "error", str(e), api_key=proxy_api_key)
|
| 94 |
+
yield format_error_message("HuggingFace API Error", str(e))
|
| 95 |
+
|
| 96 |
+
except Exception as e:
|
| 97 |
+
# Report other errors
|
| 98 |
+
if 'token_id' in locals():
|
| 99 |
+
report_token_status(token_id, "error", str(e), api_key=proxy_api_key)
|
| 100 |
+
yield format_error_message("Unexpected Error", str(e))
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def handle_chat_submit(message, history, system_msg, model_name, max_tokens, temperature, top_p):
|
| 104 |
+
"""
|
| 105 |
+
Handle chat submission and manage conversation history.
|
| 106 |
+
"""
|
| 107 |
+
if not message.strip():
|
| 108 |
+
return history, ""
|
| 109 |
+
|
| 110 |
+
# Add user message to history
|
| 111 |
+
history = history + [{"role": "user", "content": message}]
|
| 112 |
+
|
| 113 |
+
# Generate response
|
| 114 |
+
response_generator = chat_respond(
|
| 115 |
+
message,
|
| 116 |
+
history[:-1], # Don't include the current message in history for the function
|
| 117 |
+
system_msg,
|
| 118 |
+
model_name,
|
| 119 |
+
max_tokens,
|
| 120 |
+
temperature,
|
| 121 |
+
top_p
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
# Get the final response
|
| 125 |
+
assistant_response = ""
|
| 126 |
+
for partial_response in response_generator:
|
| 127 |
+
assistant_response = partial_response
|
| 128 |
+
|
| 129 |
+
# Add assistant response to history
|
| 130 |
+
history = history + [{"role": "assistant", "content": assistant_response}]
|
| 131 |
+
|
| 132 |
+
return history, ""
|
image_handler.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Image generation functionality handler for HF-Inferoxy AI Hub.
|
| 3 |
+
Handles text-to-image generation with multiple providers.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
from huggingface_hub import InferenceClient
|
| 8 |
+
from huggingface_hub.errors import HfHubHTTPError
|
| 9 |
+
from hf_token_utils import get_proxy_token, report_token_status
|
| 10 |
+
from utils import (
|
| 11 |
+
IMAGE_CONFIG,
|
| 12 |
+
validate_proxy_key,
|
| 13 |
+
format_error_message,
|
| 14 |
+
format_success_message
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def validate_dimensions(width, height):
|
| 19 |
+
"""Validate that dimensions are divisible by 8 (required by most diffusion models)"""
|
| 20 |
+
if width % 8 != 0 or height % 8 != 0:
|
| 21 |
+
return False, "Width and height must be divisible by 8"
|
| 22 |
+
return True, ""
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def generate_image(
|
| 26 |
+
prompt: str,
|
| 27 |
+
model_name: str,
|
| 28 |
+
provider: str,
|
| 29 |
+
negative_prompt: str = "",
|
| 30 |
+
width: int = IMAGE_CONFIG["width"],
|
| 31 |
+
height: int = IMAGE_CONFIG["height"],
|
| 32 |
+
num_inference_steps: int = IMAGE_CONFIG["num_inference_steps"],
|
| 33 |
+
guidance_scale: float = IMAGE_CONFIG["guidance_scale"],
|
| 34 |
+
seed: int = IMAGE_CONFIG["seed"],
|
| 35 |
+
):
|
| 36 |
+
"""
|
| 37 |
+
Generate an image using the specified model and provider through HF-Inferoxy.
|
| 38 |
+
"""
|
| 39 |
+
# Validate proxy API key
|
| 40 |
+
is_valid, error_msg = validate_proxy_key()
|
| 41 |
+
if not is_valid:
|
| 42 |
+
return None, error_msg
|
| 43 |
+
|
| 44 |
+
proxy_api_key = os.getenv("PROXY_KEY")
|
| 45 |
+
|
| 46 |
+
try:
|
| 47 |
+
# Get token from HF-Inferoxy proxy server
|
| 48 |
+
print(f"π Image: Requesting token from proxy...")
|
| 49 |
+
token, token_id = get_proxy_token(api_key=proxy_api_key)
|
| 50 |
+
print(f"β
Image: Got token: {token_id}")
|
| 51 |
+
|
| 52 |
+
print(f"π¨ Image: Using model='{model_name}', provider='{provider}'")
|
| 53 |
+
|
| 54 |
+
# Create client with specified provider
|
| 55 |
+
client = InferenceClient(
|
| 56 |
+
provider=provider,
|
| 57 |
+
api_key=token
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
print(f"π Image: Client created, preparing generation params...")
|
| 61 |
+
|
| 62 |
+
# Prepare generation parameters
|
| 63 |
+
generation_params = {
|
| 64 |
+
"model": model_name,
|
| 65 |
+
"prompt": prompt,
|
| 66 |
+
"width": width,
|
| 67 |
+
"height": height,
|
| 68 |
+
"num_inference_steps": num_inference_steps,
|
| 69 |
+
"guidance_scale": guidance_scale,
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
# Add optional parameters if provided
|
| 73 |
+
if negative_prompt:
|
| 74 |
+
generation_params["negative_prompt"] = negative_prompt
|
| 75 |
+
if seed != -1:
|
| 76 |
+
generation_params["seed"] = seed
|
| 77 |
+
|
| 78 |
+
print(f"π Image: Dimensions: {width}x{height}, steps: {num_inference_steps}, guidance: {guidance_scale}")
|
| 79 |
+
print(f"π‘ Image: Making generation request...")
|
| 80 |
+
|
| 81 |
+
# Generate image
|
| 82 |
+
image = client.text_to_image(**generation_params)
|
| 83 |
+
|
| 84 |
+
print(f"πΌοΈ Image: Generation completed! Image type: {type(image)}")
|
| 85 |
+
|
| 86 |
+
# Report successful token usage
|
| 87 |
+
report_token_status(token_id, "success", api_key=proxy_api_key)
|
| 88 |
+
|
| 89 |
+
return image, format_success_message("Image generated", f"using {model_name} on {provider}")
|
| 90 |
+
|
| 91 |
+
except HfHubHTTPError as e:
|
| 92 |
+
# Report HF Hub errors
|
| 93 |
+
if 'token_id' in locals():
|
| 94 |
+
report_token_status(token_id, "error", str(e), api_key=proxy_api_key)
|
| 95 |
+
return None, format_error_message("HuggingFace API Error", str(e))
|
| 96 |
+
|
| 97 |
+
except Exception as e:
|
| 98 |
+
# Report other errors
|
| 99 |
+
if 'token_id' in locals():
|
| 100 |
+
report_token_status(token_id, "error", str(e), api_key=proxy_api_key)
|
| 101 |
+
return None, format_error_message("Unexpected Error", str(e))
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def handle_image_generation(prompt_val, model_val, provider_val, negative_prompt_val, width_val, height_val, steps_val, guidance_val, seed_val):
|
| 105 |
+
"""
|
| 106 |
+
Handle image generation request with validation.
|
| 107 |
+
"""
|
| 108 |
+
# Validate dimensions
|
| 109 |
+
is_valid, error_msg = validate_dimensions(width_val, height_val)
|
| 110 |
+
if not is_valid:
|
| 111 |
+
return None, format_error_message("Validation Error", error_msg)
|
| 112 |
+
|
| 113 |
+
# Generate image
|
| 114 |
+
return generate_image(
|
| 115 |
+
prompt=prompt_val,
|
| 116 |
+
model_name=model_val,
|
| 117 |
+
provider=provider_val,
|
| 118 |
+
negative_prompt=negative_prompt_val,
|
| 119 |
+
width=width_val,
|
| 120 |
+
height=height_val,
|
| 121 |
+
num_inference_steps=steps_val,
|
| 122 |
+
guidance_scale=guidance_val,
|
| 123 |
+
seed=seed_val
|
| 124 |
+
)
|
ui_components.py
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
UI components for HF-Inferoxy AI Hub.
|
| 3 |
+
Contains functions to create different sections of the Gradio interface.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import gradio as gr
|
| 7 |
+
from utils import (
|
| 8 |
+
DEFAULT_CHAT_MODEL, DEFAULT_IMAGE_MODEL, DEFAULT_IMAGE_PROVIDER,
|
| 9 |
+
CHAT_CONFIG, IMAGE_CONFIG, IMAGE_PROVIDERS, IMAGE_MODEL_PRESETS,
|
| 10 |
+
IMAGE_EXAMPLE_PROMPTS
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def create_chat_tab(handle_chat_submit_fn):
|
| 15 |
+
"""
|
| 16 |
+
Create the chat tab interface.
|
| 17 |
+
"""
|
| 18 |
+
with gr.Tab("π¬ Chat Assistant", id="chat"):
|
| 19 |
+
# Chat interface at the top - most prominent
|
| 20 |
+
chatbot_display = gr.Chatbot(
|
| 21 |
+
label="Chat",
|
| 22 |
+
type="messages",
|
| 23 |
+
height=800,
|
| 24 |
+
show_copy_button=True
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
# Chat input
|
| 28 |
+
with gr.Row():
|
| 29 |
+
chat_input = gr.Textbox(
|
| 30 |
+
placeholder="Type your message here...",
|
| 31 |
+
label="Message",
|
| 32 |
+
scale=4,
|
| 33 |
+
container=False
|
| 34 |
+
)
|
| 35 |
+
chat_submit = gr.Button("Send", variant="primary", scale=1)
|
| 36 |
+
|
| 37 |
+
# Configuration options below the chat
|
| 38 |
+
with gr.Row():
|
| 39 |
+
with gr.Column(scale=1):
|
| 40 |
+
chat_model_name = gr.Textbox(
|
| 41 |
+
value=DEFAULT_CHAT_MODEL,
|
| 42 |
+
label="Model Name",
|
| 43 |
+
placeholder="e.g., openai/gpt-oss-20b or openai/gpt-oss-20b:fireworks-ai"
|
| 44 |
+
)
|
| 45 |
+
chat_system_message = gr.Textbox(
|
| 46 |
+
value=CHAT_CONFIG["system_message"],
|
| 47 |
+
label="System Message",
|
| 48 |
+
lines=2,
|
| 49 |
+
placeholder="Define the assistant's personality and behavior..."
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
with gr.Column(scale=1):
|
| 53 |
+
chat_max_tokens = gr.Slider(
|
| 54 |
+
minimum=1, maximum=4096, value=CHAT_CONFIG["max_tokens"], step=1,
|
| 55 |
+
label="Max New Tokens"
|
| 56 |
+
)
|
| 57 |
+
chat_temperature = gr.Slider(
|
| 58 |
+
minimum=0.1, maximum=2.0, value=CHAT_CONFIG["temperature"], step=0.1,
|
| 59 |
+
label="Temperature"
|
| 60 |
+
)
|
| 61 |
+
chat_top_p = gr.Slider(
|
| 62 |
+
minimum=0.1, maximum=1.0, value=CHAT_CONFIG["top_p"], step=0.05,
|
| 63 |
+
label="Top-p (nucleus sampling)"
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
# Configuration tips below the chat
|
| 67 |
+
create_chat_tips()
|
| 68 |
+
|
| 69 |
+
# Connect chat events
|
| 70 |
+
chat_submit.click(
|
| 71 |
+
fn=handle_chat_submit_fn,
|
| 72 |
+
inputs=[chat_input, chatbot_display, chat_system_message, chat_model_name,
|
| 73 |
+
chat_max_tokens, chat_temperature, chat_top_p],
|
| 74 |
+
outputs=[chatbot_display, chat_input]
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
chat_input.submit(
|
| 78 |
+
fn=handle_chat_submit_fn,
|
| 79 |
+
inputs=[chat_input, chatbot_display, chat_system_message, chat_model_name,
|
| 80 |
+
chat_max_tokens, chat_temperature, chat_top_p],
|
| 81 |
+
outputs=[chatbot_display, chat_input]
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def create_chat_tips():
|
| 86 |
+
"""Create the tips section for the chat tab."""
|
| 87 |
+
with gr.Row():
|
| 88 |
+
with gr.Column():
|
| 89 |
+
gr.Markdown("""
|
| 90 |
+
### π‘ Chat Tips
|
| 91 |
+
|
| 92 |
+
**Model Format:**
|
| 93 |
+
- Single model: `openai/gpt-oss-20b` (uses auto provider)
|
| 94 |
+
- With provider: `openai/gpt-oss-20b:fireworks-ai`
|
| 95 |
+
|
| 96 |
+
**Popular Models:**
|
| 97 |
+
- `openai/gpt-oss-20b` - Fast general purpose
|
| 98 |
+
- `meta-llama/Llama-2-7b-chat-hf` - Chat optimized
|
| 99 |
+
- `microsoft/DialoGPT-medium` - Conversation
|
| 100 |
+
- `google/flan-t5-base` - Instruction following
|
| 101 |
+
""")
|
| 102 |
+
|
| 103 |
+
with gr.Column():
|
| 104 |
+
gr.Markdown("""
|
| 105 |
+
### π Popular Providers
|
| 106 |
+
|
| 107 |
+
- **auto** - Let HF choose best provider (default)
|
| 108 |
+
- **fireworks-ai** - Fast and reliable
|
| 109 |
+
- **cerebras** - High performance
|
| 110 |
+
- **groq** - Ultra-fast inference
|
| 111 |
+
- **together** - Wide model support
|
| 112 |
+
- **cohere** - Advanced language models
|
| 113 |
+
|
| 114 |
+
**Examples:**
|
| 115 |
+
- `openai/gpt-oss-20b` (auto provider)
|
| 116 |
+
- `openai/gpt-oss-20b:fireworks-ai` (specific provider)
|
| 117 |
+
""")
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def create_image_tab(handle_image_generation_fn):
|
| 121 |
+
"""
|
| 122 |
+
Create the image generation tab interface.
|
| 123 |
+
"""
|
| 124 |
+
with gr.Tab("π¨ Image Generator", id="image"):
|
| 125 |
+
with gr.Row():
|
| 126 |
+
with gr.Column(scale=2):
|
| 127 |
+
# Image output
|
| 128 |
+
output_image = gr.Image(
|
| 129 |
+
label="Generated Image",
|
| 130 |
+
type="pil",
|
| 131 |
+
height=600,
|
| 132 |
+
show_download_button=True
|
| 133 |
+
)
|
| 134 |
+
status_text = gr.Textbox(
|
| 135 |
+
label="Generation Status",
|
| 136 |
+
interactive=False,
|
| 137 |
+
lines=2
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
with gr.Column(scale=1):
|
| 141 |
+
# Model and provider inputs
|
| 142 |
+
with gr.Group():
|
| 143 |
+
gr.Markdown("**π€ Model & Provider**")
|
| 144 |
+
img_model_name = gr.Textbox(
|
| 145 |
+
value=DEFAULT_IMAGE_MODEL,
|
| 146 |
+
label="Model Name",
|
| 147 |
+
placeholder="e.g., Qwen/Qwen-Image or stabilityai/stable-diffusion-xl-base-1.0"
|
| 148 |
+
)
|
| 149 |
+
img_provider = gr.Dropdown(
|
| 150 |
+
choices=IMAGE_PROVIDERS,
|
| 151 |
+
value=DEFAULT_IMAGE_PROVIDER,
|
| 152 |
+
label="Provider",
|
| 153 |
+
interactive=True
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
# Generation parameters
|
| 157 |
+
with gr.Group():
|
| 158 |
+
gr.Markdown("**π Prompts**")
|
| 159 |
+
img_prompt = gr.Textbox(
|
| 160 |
+
value=IMAGE_EXAMPLE_PROMPTS[0], # Use first example as default
|
| 161 |
+
label="Prompt",
|
| 162 |
+
lines=3,
|
| 163 |
+
placeholder="Describe the image you want to generate..."
|
| 164 |
+
)
|
| 165 |
+
img_negative_prompt = gr.Textbox(
|
| 166 |
+
value=IMAGE_CONFIG["negative_prompt"],
|
| 167 |
+
label="Negative Prompt",
|
| 168 |
+
lines=2,
|
| 169 |
+
placeholder="Describe what you DON'T want in the image..."
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
with gr.Group():
|
| 173 |
+
gr.Markdown("**βοΈ Generation Settings**")
|
| 174 |
+
with gr.Row():
|
| 175 |
+
img_width = gr.Slider(
|
| 176 |
+
minimum=256, maximum=2048, value=IMAGE_CONFIG["width"], step=64,
|
| 177 |
+
label="Width", info="Must be divisible by 8"
|
| 178 |
+
)
|
| 179 |
+
img_height = gr.Slider(
|
| 180 |
+
minimum=256, maximum=2048, value=IMAGE_CONFIG["height"], step=64,
|
| 181 |
+
label="Height", info="Must be divisible by 8"
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
with gr.Row():
|
| 185 |
+
img_steps = gr.Slider(
|
| 186 |
+
minimum=10, maximum=100, value=IMAGE_CONFIG["num_inference_steps"], step=1,
|
| 187 |
+
label="Inference Steps", info="More steps = better quality"
|
| 188 |
+
)
|
| 189 |
+
img_guidance = gr.Slider(
|
| 190 |
+
minimum=1.0, maximum=20.0, value=IMAGE_CONFIG["guidance_scale"], step=0.5,
|
| 191 |
+
label="Guidance Scale", info="How closely to follow prompt"
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
img_seed = gr.Slider(
|
| 195 |
+
minimum=-1, maximum=999999, value=IMAGE_CONFIG["seed"], step=1,
|
| 196 |
+
label="Seed", info="-1 for random"
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
# Generate button
|
| 200 |
+
generate_btn = gr.Button(
|
| 201 |
+
"π¨ Generate Image",
|
| 202 |
+
variant="primary",
|
| 203 |
+
size="lg",
|
| 204 |
+
scale=2
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
# Quick model presets
|
| 208 |
+
create_image_presets(img_model_name, img_provider)
|
| 209 |
+
|
| 210 |
+
# Examples for image generation
|
| 211 |
+
create_image_examples(img_prompt)
|
| 212 |
+
|
| 213 |
+
# Connect image generation events
|
| 214 |
+
generate_btn.click(
|
| 215 |
+
fn=handle_image_generation_fn,
|
| 216 |
+
inputs=[
|
| 217 |
+
img_prompt, img_model_name, img_provider, img_negative_prompt,
|
| 218 |
+
img_width, img_height, img_steps, img_guidance, img_seed
|
| 219 |
+
],
|
| 220 |
+
outputs=[output_image, status_text]
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def create_image_presets(img_model_name, img_provider):
|
| 225 |
+
"""Create quick model presets for image generation."""
|
| 226 |
+
with gr.Group():
|
| 227 |
+
gr.Markdown("**π― Popular Presets**")
|
| 228 |
+
|
| 229 |
+
for name, model, provider in IMAGE_MODEL_PRESETS:
|
| 230 |
+
btn = gr.Button(name, size="sm")
|
| 231 |
+
btn.click(
|
| 232 |
+
lambda m=model, p=provider: (m, p),
|
| 233 |
+
outputs=[img_model_name, img_provider]
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def create_image_examples(img_prompt):
|
| 238 |
+
"""Create example prompts for image generation."""
|
| 239 |
+
with gr.Group():
|
| 240 |
+
gr.Markdown("**π Example Prompts**")
|
| 241 |
+
img_examples = gr.Examples(
|
| 242 |
+
examples=[[prompt] for prompt in IMAGE_EXAMPLE_PROMPTS],
|
| 243 |
+
inputs=img_prompt
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def create_main_header():
|
| 248 |
+
"""Create the main header for the application."""
|
| 249 |
+
gr.Markdown("""
|
| 250 |
+
# π HF-Inferoxy AI Hub
|
| 251 |
+
|
| 252 |
+
A comprehensive AI platform combining chat and image generation capabilities with intelligent token management through HF-Inferoxy.
|
| 253 |
+
|
| 254 |
+
**Features:**
|
| 255 |
+
- π¬ **Smart Chat**: Conversational AI with streaming responses
|
| 256 |
+
- π¨ **Image Generation**: Text-to-image creation with multiple providers
|
| 257 |
+
- π **Intelligent Token Management**: Automatic token rotation and error handling
|
| 258 |
+
- π **Multi-Provider Support**: Works with HF Inference, Cerebras, Cohere, Groq, Together, Fal.ai, and more
|
| 259 |
+
""")
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def create_footer():
|
| 263 |
+
"""Create the footer with helpful information."""
|
| 264 |
+
gr.Markdown("""
|
| 265 |
+
---
|
| 266 |
+
### π How to Use
|
| 267 |
+
|
| 268 |
+
**Chat Tab:**
|
| 269 |
+
- Enter your message and customize the AI's behavior with system messages
|
| 270 |
+
- Choose models and providers using the format `model:provider`
|
| 271 |
+
- Adjust temperature for creativity and top-p for response diversity
|
| 272 |
+
|
| 273 |
+
**Image Tab:**
|
| 274 |
+
- Write detailed prompts describing your desired image
|
| 275 |
+
- Use negative prompts to avoid unwanted elements
|
| 276 |
+
- Experiment with different models and providers for varied styles
|
| 277 |
+
- Higher inference steps = better quality but slower generation
|
| 278 |
+
|
| 279 |
+
**Supported Providers:**
|
| 280 |
+
- **fal-ai**: High-quality image generation (default for images)
|
| 281 |
+
- **hf-inference**: Core API with comprehensive model support
|
| 282 |
+
- **cerebras**: High-performance inference
|
| 283 |
+
- **cohere**: Advanced language models with multilingual support
|
| 284 |
+
- **groq**: Ultra-fast inference, optimized for speed
|
| 285 |
+
- **together**: Collaborative AI hosting, wide model support
|
| 286 |
+
- **nebius**: Cloud-native services with enterprise features
|
| 287 |
+
- **nscale**: Optimized inference performance
|
| 288 |
+
- **replicate**: Collaborative AI hosting
|
| 289 |
+
|
| 290 |
+
**Built with β€οΈ using [HF-Inferoxy](https://nazdridoy.github.io/hf-inferoxy/) for intelligent token management**
|
| 291 |
+
""")
|
utils.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Utility functions and constants for HF-Inferoxy AI Hub.
|
| 3 |
+
Contains configuration constants and helper functions.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
# Configuration constants
|
| 10 |
+
DEFAULT_CHAT_MODEL = "openai/gpt-oss-20b"
|
| 11 |
+
DEFAULT_IMAGE_MODEL = "Qwen/Qwen-Image"
|
| 12 |
+
DEFAULT_IMAGE_PROVIDER = "fal-ai"
|
| 13 |
+
|
| 14 |
+
# Chat configuration
|
| 15 |
+
CHAT_CONFIG = {
|
| 16 |
+
"max_tokens": 1024,
|
| 17 |
+
"temperature": 0.7,
|
| 18 |
+
"top_p": 0.95,
|
| 19 |
+
"system_message": "You are a helpful and friendly AI assistant. Provide clear, accurate, and helpful responses."
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
# Image generation configuration
|
| 23 |
+
IMAGE_CONFIG = {
|
| 24 |
+
"width": 1024,
|
| 25 |
+
"height": 1024,
|
| 26 |
+
"num_inference_steps": 20,
|
| 27 |
+
"guidance_scale": 7.5,
|
| 28 |
+
"seed": -1,
|
| 29 |
+
"negative_prompt": "blurry, low quality, distorted, deformed, ugly, bad anatomy"
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
# Supported providers
|
| 33 |
+
CHAT_PROVIDERS = ["auto", "fireworks-ai", "cerebras", "groq", "together", "cohere"]
|
| 34 |
+
IMAGE_PROVIDERS = ["hf-inference", "fal-ai", "nebius", "nscale", "replicate", "together"]
|
| 35 |
+
|
| 36 |
+
# Popular models for quick access
|
| 37 |
+
POPULAR_CHAT_MODELS = [
|
| 38 |
+
"openai/gpt-oss-20b",
|
| 39 |
+
"meta-llama/Llama-2-7b-chat-hf",
|
| 40 |
+
"microsoft/DialoGPT-medium",
|
| 41 |
+
"google/flan-t5-base"
|
| 42 |
+
]
|
| 43 |
+
|
| 44 |
+
POPULAR_IMAGE_MODELS = [
|
| 45 |
+
"Qwen/Qwen-Image",
|
| 46 |
+
"black-forest-labs/FLUX.1-dev",
|
| 47 |
+
"stabilityai/stable-diffusion-xl-base-1.0",
|
| 48 |
+
"runwayml/stable-diffusion-v1-5"
|
| 49 |
+
]
|
| 50 |
+
|
| 51 |
+
# Model presets for image generation
|
| 52 |
+
IMAGE_MODEL_PRESETS = [
|
| 53 |
+
("Qwen (Fal.ai)", "Qwen/Qwen-Image", "fal-ai"),
|
| 54 |
+
("Qwen (Replicate)", "Qwen/Qwen-Image", "replicate"),
|
| 55 |
+
("FLUX.1 (Nebius)", "black-forest-labs/FLUX.1-dev", "nebius"),
|
| 56 |
+
("SDXL (HF)", "stabilityai/stable-diffusion-xl-base-1.0", "hf-inference"),
|
| 57 |
+
]
|
| 58 |
+
|
| 59 |
+
# Example prompts for image generation
|
| 60 |
+
IMAGE_EXAMPLE_PROMPTS = [
|
| 61 |
+
"A majestic dragon flying over a medieval castle, epic fantasy art, detailed, 8k",
|
| 62 |
+
"A serene Japanese garden with cherry blossoms, zen atmosphere, peaceful, high quality",
|
| 63 |
+
"A futuristic cityscape with flying cars and neon lights, cyberpunk style, cinematic",
|
| 64 |
+
"A cute robot cat playing with yarn, adorable, cartoon style, vibrant colors",
|
| 65 |
+
"A magical forest with glowing mushrooms and fairy lights, fantasy, ethereal beauty",
|
| 66 |
+
"Portrait of a wise old wizard with flowing robes, magical aura, fantasy character art",
|
| 67 |
+
"A cozy coffee shop on a rainy day, warm lighting, peaceful atmosphere, detailed",
|
| 68 |
+
"An astronaut floating in space with Earth in background, photorealistic, stunning"
|
| 69 |
+
]
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def get_proxy_key():
|
| 73 |
+
"""Get the proxy API key from environment variables."""
|
| 74 |
+
return os.getenv("PROXY_KEY")
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def validate_proxy_key():
|
| 78 |
+
"""Validate that the proxy key is available."""
|
| 79 |
+
proxy_key = get_proxy_key()
|
| 80 |
+
if not proxy_key:
|
| 81 |
+
return False, "β Error: PROXY_KEY not found in environment variables. Please set it in your HuggingFace Space secrets."
|
| 82 |
+
return True, ""
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def parse_model_and_provider(model_name):
|
| 86 |
+
"""
|
| 87 |
+
Parse model name and provider from a string like 'model:provider'.
|
| 88 |
+
Returns (model, provider) tuple. Provider is None if not specified.
|
| 89 |
+
"""
|
| 90 |
+
if ":" in model_name:
|
| 91 |
+
model, provider = model_name.split(":", 1)
|
| 92 |
+
return model, provider
|
| 93 |
+
else:
|
| 94 |
+
return model_name, None
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def format_error_message(error_type, error_message):
|
| 98 |
+
"""Format error messages consistently."""
|
| 99 |
+
return f"β {error_type}: {error_message}"
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def format_success_message(operation, details=""):
|
| 103 |
+
"""Format success messages consistently."""
|
| 104 |
+
base_message = f"β
{operation} completed successfully"
|
| 105 |
+
if details:
|
| 106 |
+
return f"{base_message}: {details}"
|
| 107 |
+
return f"{base_message}!"
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def get_gradio_theme():
|
| 111 |
+
"""Get the default Gradio theme for the application."""
|
| 112 |
+
try:
|
| 113 |
+
import gradio as gr
|
| 114 |
+
return gr.themes.Soft()
|
| 115 |
+
except ImportError:
|
| 116 |
+
return None
|