snackshell commited on
Commit
4cda5f1
·
verified ·
1 Parent(s): 3665d0a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -42
app.py CHANGED
@@ -13,12 +13,12 @@ API_URL = f"https://api-inference.huggingface.co/models/{MODEL_NAME}"
13
  headers = {"Authorization": f"Bearer {HF_API_TOKEN}"}
14
  WATERMARK_TEXT = "SelamGPT"
15
  MAX_RETRIES = 3
16
- TIMEOUT = 60
17
- EXECUTOR = ThreadPoolExecutor(max_workers=2)
18
 
19
- # ===== WATERMARK FUNCTION =====
20
  def add_watermark(image_bytes):
21
- """Add watermark with optimized PNG output"""
22
  try:
23
  image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
24
  draw = ImageDraw.Draw(image)
@@ -36,69 +36,66 @@ def add_watermark(image_bytes):
36
  draw.text((x+1, y+1), WATERMARK_TEXT, font=font, fill=(0, 0, 0, 128))
37
  draw.text((x, y), WATERMARK_TEXT, font=font, fill=(255, 255, 255))
38
 
39
- # Convert to optimized PNG
40
- img_byte_arr = io.BytesIO()
41
- image.save(img_byte_arr, format='PNG', optimize=True, quality=85)
42
- img_byte_arr.seek(0)
43
- return Image.open(img_byte_arr)
44
  except Exception as e:
45
  print(f"Watermark error: {str(e)}")
46
  return Image.open(io.BytesIO(image_bytes))
47
 
48
- # ===== IMAGE GENERATION =====
49
  def generate_image(prompt):
50
  if not prompt.strip():
51
  return None, "⚠️ Please enter a prompt"
52
 
 
 
 
 
 
 
 
 
 
53
  def api_call():
54
  return requests.post(
55
  API_URL,
56
  headers=headers,
57
  json={
58
  "inputs": prompt,
59
- "parameters": {
60
- "height": 1024,
61
- "width": 1024,
62
- "num_inference_steps": 30
63
- },
64
- "options": {"wait_for_model": True}
65
  },
66
  timeout=TIMEOUT
67
  )
68
 
69
  for attempt in range(MAX_RETRIES):
70
  try:
71
- future = EXECUTOR.submit(api_call)
72
- response = future.result()
73
 
74
  if response.status_code == 200:
75
- return add_watermark(response.content), "✔️ Generation successful"
 
76
  elif response.status_code == 503:
77
- wait_time = (attempt + 1) * 15
78
- print(f"Model loading, waiting {wait_time}s...")
79
- time.sleep(wait_time)
80
  continue
81
  else:
82
  return None, f"⚠️ API Error: {response.text[:200]}"
83
  except requests.Timeout:
84
- return None, f"⚠️ Timeout: Model took >{TIMEOUT}s to respond"
85
  except Exception as e:
86
- return None, f"⚠️ Unexpected error: {str(e)[:200]}"
87
 
88
- return None, "⚠️ Failed after multiple attempts. Please try later."
89
-
90
- # ===== GRADIO THEME =====
91
- theme = gr.themes.Default(
92
- primary_hue="emerald",
93
- secondary_hue="amber",
94
- font=[gr.themes.GoogleFont("Poppins"), "Arial", "sans-serif"]
95
- )
96
 
97
  # ===== GRADIO INTERFACE =====
98
- with gr.Blocks(theme=theme, title="SelamGPT Image Generator") as demo:
99
  gr.Markdown("""
100
  # 🎨 SelamGPT Image Generator
101
- *Powered by Stable Diffusion XL (1024x1024 PNG output)*
102
  """)
103
 
104
  with gr.Row():
@@ -106,8 +103,7 @@ with gr.Blocks(theme=theme, title="SelamGPT Image Generator") as demo:
106
  prompt_input = gr.Textbox(
107
  label="Describe your image",
108
  placeholder="A futuristic Ethiopian city with flying cars...",
109
- lines=3,
110
- max_lines=5
111
  )
112
  with gr.Row():
113
  generate_btn = gr.Button("Generate Image", variant="primary")
@@ -115,18 +111,18 @@ with gr.Blocks(theme=theme, title="SelamGPT Image Generator") as demo:
115
 
116
  gr.Examples(
117
  examples=[
118
- ["An ancient Aksumite warrior in cyberpunk armor, 4k detailed"],
119
- ["Traditional Ethiopian coffee ceremony in zero gravity"],
120
- ["Portrait of a Habesha queen with golden jewelry"]
121
  ],
122
  inputs=prompt_input
123
  )
124
 
125
  with gr.Column(scale=2):
126
  output_image = gr.Image(
127
- label="Generated Image",
128
  type="pil",
129
- format="png",
130
  height=512
131
  )
132
  status_output = gr.Textbox(
@@ -147,5 +143,5 @@ with gr.Blocks(theme=theme, title="SelamGPT Image Generator") as demo:
147
  )
148
 
149
  if __name__ == "__main__":
150
- demo.queue(max_size=2)
151
  demo.launch(server_name="0.0.0.0", server_port=7860)
 
13
  headers = {"Authorization": f"Bearer {HF_API_TOKEN}"}
14
  WATERMARK_TEXT = "SelamGPT"
15
  MAX_RETRIES = 3
16
+ TIMEOUT = 45 # Reduced timeout for faster failover
17
+ EXECUTOR = ThreadPoolExecutor(max_workers=3) # Increased workers
18
 
19
+ # ===== OPTIMIZED WATERMARK FUNCTION (WebP) =====
20
  def add_watermark(image_bytes):
21
+ """Add watermark with optimized WebP output (85% quality)"""
22
  try:
23
  image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
24
  draw = ImageDraw.Draw(image)
 
36
  draw.text((x+1, y+1), WATERMARK_TEXT, font=font, fill=(0, 0, 0, 128))
37
  draw.text((x, y), WATERMARK_TEXT, font=font, fill=(255, 255, 255))
38
 
39
+ # Convert to WebP (faster + smaller)
40
+ webp_buffer = io.BytesIO()
41
+ image.save(webp_buffer, format="WEBP", quality=85, method=6) # 85% quality, best compression
42
+ webp_buffer.seek(0)
43
+ return Image.open(webp_buffer)
44
  except Exception as e:
45
  print(f"Watermark error: {str(e)}")
46
  return Image.open(io.BytesIO(image_bytes))
47
 
48
+ # ===== FASTER IMAGE GENERATION =====
49
  def generate_image(prompt):
50
  if not prompt.strip():
51
  return None, "⚠️ Please enter a prompt"
52
 
53
+ # Faster generation parameters
54
+ params = {
55
+ "height": 768, # Slightly smaller = faster
56
+ "width": 768,
57
+ "num_inference_steps": 20, # Reduced from 30
58
+ "guidance_scale": 7.0, # Slightly lower for speed
59
+ "options": {"wait_for_model": False} # Don't wait if model is loading
60
+ }
61
+
62
  def api_call():
63
  return requests.post(
64
  API_URL,
65
  headers=headers,
66
  json={
67
  "inputs": prompt,
68
+ "parameters": params
 
 
 
 
 
69
  },
70
  timeout=TIMEOUT
71
  )
72
 
73
  for attempt in range(MAX_RETRIES):
74
  try:
75
+ start_time = time.time()
76
+ response = EXECUTOR.submit(api_call).result()
77
 
78
  if response.status_code == 200:
79
+ gen_time = time.time() - start_time
80
+ return add_watermark(response.content), f"✔️ Generated in {gen_time:.1f}s"
81
  elif response.status_code == 503:
82
+ if attempt < MAX_RETRIES - 1:
83
+ time.sleep(5 * (attempt + 1)) # Progressive backoff
 
84
  continue
85
  else:
86
  return None, f"⚠️ API Error: {response.text[:200]}"
87
  except requests.Timeout:
88
+ return None, f"⚠️ Timeout: Model took >{TIMEOUT}s"
89
  except Exception as e:
90
+ return None, f"⚠️ Error: {str(e)[:200]}"
91
 
92
+ return None, "⚠️ Failed after retries. Try again."
 
 
 
 
 
 
 
93
 
94
  # ===== GRADIO INTERFACE =====
95
+ with gr.Blocks(title="SelamGPT Image Generator") as demo:
96
  gr.Markdown("""
97
  # 🎨 SelamGPT Image Generator
98
+ *Optimized for speed (WebP output @ 768px)*
99
  """)
100
 
101
  with gr.Row():
 
103
  prompt_input = gr.Textbox(
104
  label="Describe your image",
105
  placeholder="A futuristic Ethiopian city with flying cars...",
106
+ lines=3
 
107
  )
108
  with gr.Row():
109
  generate_btn = gr.Button("Generate Image", variant="primary")
 
111
 
112
  gr.Examples(
113
  examples=[
114
+ ["An ancient Aksumite warrior in cyberpunk armor"],
115
+ ["Traditional Ethiopian coffee ceremony"],
116
+ ["Habesha queen with jewelry"]
117
  ],
118
  inputs=prompt_input
119
  )
120
 
121
  with gr.Column(scale=2):
122
  output_image = gr.Image(
123
+ label="Generated Image (WebP)",
124
  type="pil",
125
+ format="webp", # WebP output
126
  height=512
127
  )
128
  status_output = gr.Textbox(
 
143
  )
144
 
145
  if __name__ == "__main__":
146
+ demo.queue(concurrency_count=3) # Increased concurrency
147
  demo.launch(server_name="0.0.0.0", server_port=7860)