marahmerah commited on
Commit
eac94ad
·
verified ·
1 Parent(s): 753d150

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +91 -74
app.py CHANGED
@@ -6,7 +6,6 @@ import os
6
  import time
7
  from PIL import Image
8
  from deep_translator import GoogleTranslator
9
- import json
10
 
11
  # Project by Nymbo
12
 
@@ -15,25 +14,39 @@ API_TOKEN = os.getenv("HF_READ_TOKEN")
15
  headers = {"Authorization": f"Bearer {API_TOKEN}"}
16
  timeout = 100
17
 
18
- # Function to query the API and return the generated image as PNG
19
- def query(prompt, is_negative=False, steps=35, cfg_scale=7, sampler="DPM++ 2M Karras", seed=-1, strength=0.7, width=1024, height=1024):
20
- if prompt == "" or prompt is None:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  return None
22
 
23
  key = random.randint(0, 999)
24
-
25
  API_TOKEN = random.choice([os.getenv("HF_READ_TOKEN")])
26
  headers = {"Authorization": f"Bearer {API_TOKEN}"}
27
 
28
- # Translate the prompt from Indonesian to English
29
- prompt = GoogleTranslator(source='id', target='en').translate(prompt)
30
- print(f'\033[1mGeneration {key} translation:\033[0m {prompt}')
31
-
32
- # Enhance the prompt
33
- prompt = f"{prompt} | ultra detail, ultra elaboration, ultra quality, perfect."
 
 
34
  print(f'\033[1mGeneration {key}:\033[0m {prompt}')
35
 
36
- # Prepare the payload
37
  payload = {
38
  "inputs": prompt,
39
  "is_negative": is_negative,
@@ -41,50 +54,52 @@ def query(prompt, is_negative=False, steps=35, cfg_scale=7, sampler="DPM++ 2M Ka
41
  "cfg_scale": cfg_scale,
42
  "seed": seed if seed != -1 else random.randint(1, 1000000000),
43
  "strength": strength,
44
- "parameters": {
45
- "width": width,
46
- "height": height
47
- }
48
  }
49
 
50
- # API request
51
- response = requests.post(API_URL, headers=headers, json=payload, timeout=timeout)
52
- if response.status_code != 200:
53
- print(f"Error: Failed to get image. Response status: {response.status_code}")
54
- print(f"Response content: {response.text}")
55
- if response.status_code == 503:
56
- raise gr.Error(f"{response.status_code} : The model is being loaded")
57
- raise gr.Error(f"{response.status_code}")
58
-
59
  try:
60
- # Convert to PNG
61
- image_bytes = response.content
62
- img = Image.open(io.BytesIO(image_bytes))
 
 
 
63
 
64
- # Create PNG in memory
65
- png_buffer = io.BytesIO()
66
- img.save(png_buffer, format="PNG")
67
- png_buffer.seek(0)
68
- png_image = Image.open(png_buffer)
69
 
70
- print(f'\033[1mGeneration {key} completed!\033[0m ({prompt})')
71
- return png_image
 
 
 
 
 
72
  except Exception as e:
73
- print(f"Error when trying to open the image: {e}")
74
- return None
75
 
76
- # CSS styling
77
  css = """
78
  #app-container {
79
  max-width: 800px;
80
- margin-left: auto;
81
- margin-right: auto;
 
 
 
 
 
 
 
 
 
 
82
  }
83
  """
84
 
85
- # Gradio UI
86
  with gr.Blocks(theme='Nymbo/Nymbo_Theme', css=css) as app:
87
- gr.HTML("<center><h1>FLUX.1-Dev</h1></center>")
88
 
89
  with gr.Column(elem_id="app-container"):
90
  with gr.Row():
@@ -92,44 +107,46 @@ with gr.Blocks(theme='Nymbo/Nymbo_Theme', css=css) as app:
92
  with gr.Row():
93
  text_prompt = gr.Textbox(
94
  label="Prompt",
95
- placeholder="Enter a prompt here",
96
- lines=2,
97
  elem_id="prompt-text-input"
98
  )
99
 
100
- with gr.Row():
101
- with gr.Accordion("Advanced Settings", open=False):
102
- negative_prompt = gr.Textbox(
103
- label="Negative Prompt",
104
- placeholder="What should not be in the image",
105
- value="(deformed, distorted, disfigured), poorly drawn, bad anatomy, wrong anatomy, extra limb, missing limb, floating limbs, (mutated hands and fingers), disconnected limbs, mutation, mutated, ugly, disgusting, blurry, amputation, misspellings, typos",
106
- lines=3,
107
- elem_id="negative-prompt-text-input"
108
- )
109
- with gr.Row():
110
- width = gr.Slider(label="Width", value=1024, minimum=64, maximum=1216, step=32)
111
- height = gr.Slider(label="Height", value=1024, minimum=64, maximum=1216, step=32)
112
- steps = gr.Slider(label="Sampling steps", value=35, minimum=1, maximum=100, step=1)
113
- cfg = gr.Slider(label="CFG Scale", value=7, minimum=1, maximum=20, step=1)
114
- strength = gr.Slider(label="Strength", value=0.7, minimum=0, maximum=1, step=0.001)
115
- seed = gr.Slider(label="Seed", value=-1, minimum=-1, maximum=1000000000, step=1)
116
- method = gr.Radio(
117
- label="Sampling method",
118
- value="DPM++ 2M Karras",
119
- choices=["DPM++ 2M Karras", "DPM++ SDE Karras", "Euler", "Euler a", "Heun", "DDIM"]
120
- )
121
 
122
- with gr.Row():
123
- text_button = gr.Button("Run", variant='primary', elem_id="gen-button")
124
 
125
  with gr.Row():
126
- image_output = gr.Image(type="pil", label="Image Output", elem_id="gallery")
 
 
 
 
 
127
 
128
- text_button.click(
129
- query,
130
- inputs=[text_prompt, negative_prompt, steps, cfg, method, seed, strength, width, height],
131
- outputs=image_output
132
  )
133
 
134
- # Launch the app
135
- app.launch(show_api=True, share=True)
 
6
  import time
7
  from PIL import Image
8
  from deep_translator import GoogleTranslator
 
9
 
10
  # Project by Nymbo
11
 
 
14
  headers = {"Authorization": f"Bearer {API_TOKEN}"}
15
  timeout = 100
16
 
17
+ def convert_to_png(image):
18
+ """Convert any image format to true PNG format"""
19
+ png_buffer = io.BytesIO()
20
+ if image.mode == 'RGBA':
21
+ # If image has alpha channel, save as PNG with transparency
22
+ image.save(png_buffer, format='PNG', optimize=True)
23
+ else:
24
+ # Convert to RGB first if not in RGB/RGBA mode
25
+ if image.mode != 'RGB':
26
+ image = image.convert('RGB')
27
+ image.save(png_buffer, format='PNG', optimize=True)
28
+ png_buffer.seek(0)
29
+ return Image.open(png_buffer)
30
+
31
+ def query(prompt, is_negative=False, steps=35, cfg_scale=7, sampler="DPM++ 2M Karras",
32
+ seed=-1, strength=0.7, width=1024, height=1024):
33
+ if not prompt:
34
  return None
35
 
36
  key = random.randint(0, 999)
 
37
  API_TOKEN = random.choice([os.getenv("HF_READ_TOKEN")])
38
  headers = {"Authorization": f"Bearer {API_TOKEN}"}
39
 
40
+ # Translate prompt
41
+ try:
42
+ prompt = GoogleTranslator(source='id', target='en').translate(prompt)
43
+ print(f'\033[1mGeneration {key} translation:\033[0m {prompt}')
44
+ prompt = f"{prompt} | ultra detail, ultra elaboration, ultra quality, perfect."
45
+ except Exception as e:
46
+ print(f"Translation error: {e}")
47
+
48
  print(f'\033[1mGeneration {key}:\033[0m {prompt}')
49
 
 
50
  payload = {
51
  "inputs": prompt,
52
  "is_negative": is_negative,
 
54
  "cfg_scale": cfg_scale,
55
  "seed": seed if seed != -1 else random.randint(1, 1000000000),
56
  "strength": strength,
57
+ "parameters": {"width": width, "height": height}
 
 
 
58
  }
59
 
 
 
 
 
 
 
 
 
 
60
  try:
61
+ response = requests.post(API_URL, headers=headers, json=payload, timeout=timeout)
62
+ response.raise_for_status()
63
+
64
+ # Convert directly to PNG without intermediate format
65
+ img = Image.open(io.BytesIO(response.content))
66
+ png_img = convert_to_png(img)
67
 
68
+ print(f'\033[1mGeneration {key} completed as PNG!\033[0m')
69
+ return png_img
 
 
 
70
 
71
+ except requests.exceptions.RequestException as e:
72
+ print(f"API Error: {e}")
73
+ if hasattr(e, 'response') and e.response:
74
+ if e.response.status_code == 503:
75
+ raise gr.Error("503: Model is loading, please try again later")
76
+ raise gr.Error(f"{e.response.status_code}: {e.response.text}")
77
+ raise gr.Error("Network error occurred")
78
  except Exception as e:
79
+ print(f"Image processing error: {e}")
80
+ raise gr.Error(f"Image processing failed: {str(e)}")
81
 
82
+ # Improved CSS
83
  css = """
84
  #app-container {
85
  max-width: 800px;
86
+ margin: 0 auto;
87
+ padding: 20px;
88
+ }
89
+ #prompt-text-input, #negative-prompt-text-input {
90
+ font-size: 14px;
91
+ }
92
+ #gallery {
93
+ min-height: 512px;
94
+ background: #f5f5f5;
95
+ }
96
+ #gen-button {
97
+ margin: 10px 0;
98
  }
99
  """
100
 
 
101
  with gr.Blocks(theme='Nymbo/Nymbo_Theme', css=css) as app:
102
+ gr.HTML("<center><h1>FLUX.1-Dev (PNG Output)</h1></center>")
103
 
104
  with gr.Column(elem_id="app-container"):
105
  with gr.Row():
 
107
  with gr.Row():
108
  text_prompt = gr.Textbox(
109
  label="Prompt",
110
+ placeholder="Masukkan prompt dalam Bahasa Indonesia",
111
+ lines=2,
112
  elem_id="prompt-text-input"
113
  )
114
 
115
+ with gr.Accordion("Advanced Settings", open=False):
116
+ negative_prompt = gr.Textbox(
117
+ label="Negative Prompt",
118
+ value="(deformed, distorted, disfigured), poorly drawn, bad anatomy, wrong anatomy, extra limb, missing limb, floating limbs, (mutated hands and fingers), disconnected limbs, mutation, mutated, ugly, disgusting, blurry, amputation",
119
+ lines=3
120
+ )
121
+ with gr.Row():
122
+ width = gr.Slider(1024, label="Width", minimum=512, maximum=1536, step=64)
123
+ height = gr.Slider(1024, label="Height", minimum=512, maximum=1536, step=64)
124
+ with gr.Row():
125
+ steps = gr.Slider(35, label="Steps", minimum=10, maximum=100, step=1)
126
+ cfg = gr.Slider(7.0, label="CFG Scale", minimum=1.0, maximum=20.0, step=0.5)
127
+ with gr.Row():
128
+ strength = gr.Slider(0.7, label="Strength", minimum=0.1, maximum=1.0, step=0.01)
129
+ seed = gr.Number(-1, label="Seed (-1 for random)")
130
+ method = gr.Radio(
131
+ ["DPM++ 2M Karras", "DPM++ SDE Karras", "Euler", "Euler a", "Heun", "DDIM"],
132
+ value="DPM++ 2M Karras",
133
+ label="Sampling Method"
134
+ )
 
135
 
136
+ generate_btn = gr.Button("Generate Image", variant="primary")
 
137
 
138
  with gr.Row():
139
+ output_image = gr.Image(
140
+ type="pil",
141
+ label="Generated PNG Image",
142
+ format="png", # Explicitly set output format
143
+ elem_id="gallery"
144
+ )
145
 
146
+ generate_btn.click(
147
+ fn=query,
148
+ inputs=[text_prompt, negative_prompt, steps, cfg, method, seed, strength, width, height],
149
+ outputs=output_image
150
  )
151
 
152
+ app.launch(server_name="0.0.0.0", server_port=7860, share=True)