snackshell commited on
Commit
882e052
Β·
verified Β·
1 Parent(s): b25c1db

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +102 -56
app.py CHANGED
@@ -1,64 +1,110 @@
 
 
1
  import gradio as gr
2
- from diffusers import AutoPipelineForText2Image
3
  from PIL import Image, ImageDraw, ImageFont
4
- import torch
5
- import random
6
 
7
- device = "cuda" if torch.cuda.is_available() else "cpu"
 
 
 
 
 
 
8
 
9
- pipe = AutoPipelineForText2Image.from_pretrained(
10
- "stabilityai/sdxl-turbo",
11
- torch_dtype=torch.float16 if device == "cuda" else torch.float32,
12
- variant="fp16" if device == "cuda" else None
13
- )
14
- pipe = pipe.to(device)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
- MAX_SEED = 2**32 - 1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
- def add_watermark(image):
19
- draw = ImageDraw.Draw(image)
20
- font = ImageFont.load_default()
21
- text = "SelamGPT"
22
- margin = 10
23
- x = image.width - draw.textlength(text, font=font) - margin
24
- y = image.height - 20
25
- draw.text((x, y), text, font=font, fill=(255, 255, 255))
26
- return image
27
-
28
- def generate(prompt, seed, randomize_seed):
29
- if randomize_seed or seed == 0:
30
- seed = random.randint(0, MAX_SEED)
31
- generator = torch.Generator(device=device).manual_seed(seed)
32
-
33
- image = pipe(
34
- prompt=prompt,
35
- num_inference_steps=2,
36
- guidance_scale=0.0,
37
- generator=generator,
38
- ).images[0]
39
-
40
- image = add_watermark(image)
41
- return image, seed
42
-
43
- examples = [
44
- "Futuristic Ethiopian city at sunset, detailed, cinematic",
45
- "αŠ αŠ•α‹΅ ጫካ α‹αˆ΅αŒ₯ α‹¨α‰°αˆ°α‹ˆαˆ¨ α‹¨αˆ³α‹­α‰£αˆ­ αŠ¨α‰°αˆ› α‰ αˆ˜αˆ΅αˆŽ α‹¨α‰³αˆ°αˆ¨ ቀይ α‰₯αˆ­αˆƒαŠ•",
46
- ]
47
-
48
- with gr.Blocks() as demo:
49
- gr.Markdown("## 🎨 SelamGPT - Super Fast Text-to-Image Generator")
50
-
51
- prompt = gr.Textbox(label="Prompt", placeholder="Type your idea in English or Amharic")
52
- run = gr.Button("Generate")
53
-
54
- result = gr.Image(label="Generated Image")
55
- with gr.Accordion("Advanced Settings", open=False):
56
- seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0)
57
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
58
-
59
- gr.Examples(examples=examples, inputs=[prompt])
60
-
61
- run.click(fn=generate, inputs=[prompt, seed, randomize_seed], outputs=[result, seed])
62
 
63
  if __name__ == "__main__":
64
- demo.launch()
 
1
+ import os
2
+ import requests
3
  import gradio as gr
 
4
  from PIL import Image, ImageDraw, ImageFont
5
+ import io
6
+ import time
7
 
8
+ # Configuration
9
+ HF_API_TOKEN = os.environ.get("HF_API_TOKEN")
10
+ MODEL_NAME = "stabilityai/stable-diffusion-xl-base-1.0" # High-quality model
11
+ API_URL = f"https://api-inference.huggingface.co/models/{MODEL_NAME}"
12
+ headers = {"Authorization": f"Bearer {HF_API_TOKEN}"}
13
+ WATERMARK_TEXT = "SelamGPT"
14
+ MAX_RETRIES = 3
15
 
16
+ def add_watermark(image_bytes):
17
+ """Add watermark to generated image"""
18
+ try:
19
+ image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
20
+ draw = ImageDraw.Draw(image)
21
+
22
+ # Use default font (no need for external files)
23
+ try:
24
+ font = ImageFont.truetype("arialbd.ttf", 40)
25
+ except:
26
+ font = ImageFont.load_default(size=40) # Fallback
27
+
28
+ # Calculate text position (bottom-right corner)
29
+ bbox = draw.textbbox((0, 0), WATERMARK_TEXT, font=font)
30
+ text_width = bbox[2] - bbox[0]
31
+ text_height = bbox[3] - bbox[1]
32
+ margin = 20
33
+ position = (image.width - text_width - margin, image.height - text_height - margin)
34
+
35
+ # Draw watermark with semi-transparent white text and black outline
36
+ draw.text(
37
+ position,
38
+ WATERMARK_TEXT,
39
+ font=font,
40
+ fill=(255, 255, 255, 128),
41
+ stroke_width=2,
42
+ stroke_fill=(0, 0, 0, 128)
43
+ )
44
+
45
+ return image
46
+ except Exception as e:
47
+ print(f"Watermark error: {str(e)}")
48
+ return Image.open(io.BytesIO(image_bytes)) # Return original if watermark fails
49
 
50
+ def generate_image(prompt):
51
+ """Generate image with retry logic"""
52
+ if not prompt.strip():
53
+ return "Error: Please enter a valid prompt"
54
+
55
+ for attempt in range(MAX_RETRIES):
56
+ try:
57
+ response = requests.post(
58
+ API_URL,
59
+ headers=headers,
60
+ json={"inputs": prompt, "options": {"wait_for_model": True}},
61
+ timeout=30
62
+ )
63
+
64
+ if response.status_code == 200:
65
+ return add_watermark(response.content)
66
+ elif response.status_code == 503: # Model loading
67
+ time.sleep(10 * (attempt + 1)) # Exponential backoff
68
+ continue
69
+ else:
70
+ return f"API Error: {response.text}"
71
+ except requests.Timeout:
72
+ return "Error: Request timed out (30s)"
73
+ except Exception as e:
74
+ return f"Unexpected error: {str(e)}"
75
+
76
+ return "Failed after multiple attempts. Try again later."
77
 
78
+ # Gradio Interface
79
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
80
+ gr.Markdown("""
81
+ # 🎨 SelamGPT Image Generator
82
+ *Powered by Stable Diffusion XL with built-in watermark*
83
+ """)
84
+
85
+ with gr.Row():
86
+ with gr.Column():
87
+ prompt_input = gr.Textbox(
88
+ label="Describe your image",
89
+ placeholder="A futuristic city at sunset...",
90
+ lines=3
91
+ )
92
+ generate_btn = gr.Button("Generate", variant="primary")
93
+ examples = gr.Examples(
94
+ examples=["A cute robot reading a book", "Ethiopian landscape in oil painting style"],
95
+ inputs=prompt_input
96
+ )
97
+
98
+ with gr.Column():
99
+ output_image = gr.Image(label="Generated Image", height=512)
100
+ error_output = gr.Textbox(label="Status", visible=False)
101
+
102
+ generate_btn.click(
103
+ fn=generate_image,
104
+ inputs=prompt_input,
105
+ outputs=[output_image, error_output],
106
+ show_progress="full"
107
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
 
109
  if __name__ == "__main__":
110
+ demo.launch(server_name="0.0.0.0", server_port=7860)