SLSLK commited on
Commit
f0f8078
·
verified ·
1 Parent(s): 3503531

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +115 -142
app.py CHANGED
@@ -3,25 +3,22 @@ from gradio_client import Client, handle_file
3
  import re
4
  import threading
5
  import time
6
- import tempfile
7
  import requests
8
  import os
9
  import uuid
 
10
 
11
  # ---------------------------
12
- # Setup Storage (persistent)
13
  # ---------------------------
14
  IMAGE_DIR = "data/images"
15
  os.makedirs(IMAGE_DIR, exist_ok=True)
16
 
17
- # ---------------------------
18
- # Clients
19
- # ---------------------------
20
  client_main = Client("selfit-camera/Omni-Image-Editor")
21
- client_process = Client("Galaxydude2/aaaaa")
22
 
23
  # ---------------------------
24
- # Session State
25
  # ---------------------------
26
  if "gallery" not in st.session_state:
27
  st.session_state.gallery = []
@@ -33,7 +30,7 @@ if "page" not in st.session_state:
33
  st.session_state.page = "🖼️ Generieren"
34
 
35
  # ---------------------------
36
- # Helpers
37
  # ---------------------------
38
  def extract_url(html):
39
  match = re.search(r"src='([^']+)'", html)
@@ -44,37 +41,41 @@ def save_image_from_url(url):
44
  try:
45
  r = requests.get(url)
46
  if r.status_code != 200:
47
- st.error(f"❌ Download Error: HTTP {r.status_code}")
48
  return None
49
 
50
- filename = f"{uuid.uuid4()}.png"
51
- path = os.path.join(IMAGE_DIR, filename)
52
-
53
  with open(path, "wb") as f:
54
  f.write(r.content)
55
 
56
  return path
57
-
58
  except Exception as e:
59
  st.error(f"❌ Save Error: {e}")
60
  return None
61
 
62
 
63
- def prepare_image(input_image):
64
- # ❌ block gradio tmp
65
- if isinstance(input_image, str) and "/tmp/gradio" in input_image:
66
- st.error("❌ Invalid temp path from gradio")
67
- return None
 
68
 
69
- # 🌐 URL → speichern
70
- if isinstance(input_image, str) and input_image.startswith("http"):
71
- local_path = save_image_from_url(input_image)
72
- if not local_path:
 
 
 
 
 
 
73
  return None
74
- return handle_file(local_path)
75
 
76
- # 📁 local file
77
- return handle_file(input_image)
 
78
 
79
 
80
  # ---------------------------
@@ -95,12 +96,21 @@ def generate_image(prompt):
95
 
96
  def edit_image(input_image, prompt):
97
  try:
98
- image_input = prepare_image(input_image)
99
- if not image_input:
 
 
 
 
 
 
 
 
 
100
  return None
101
 
102
  result = client_main.predict(
103
- input_image=image_input,
104
  prompt=prompt,
105
  api_name="/edit_image_interface"
106
  )
@@ -114,9 +124,13 @@ def edit_image(input_image, prompt):
114
 
115
  def process_image(input_image):
116
  try:
117
- image_input = prepare_image(input_image)
118
- if not image_input:
119
- return None
 
 
 
 
120
 
121
  result = client_process.predict(
122
  image=image_input,
@@ -131,27 +145,40 @@ def process_image(input_image):
131
 
132
 
133
  # ---------------------------
134
- # Async Helper
135
  # ---------------------------
136
- def run_with_progress(func, *args):
137
- result_container = {"result": None, "done": False}
138
 
139
  def task():
140
- result_container["result"] = func(*args)
141
- result_container["done"] = True
142
 
143
  threading.Thread(target=task).start()
144
- return result_container
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
 
146
 
147
  # ---------------------------
148
  # UI
149
  # ---------------------------
150
- st.set_page_config(page_title="Omni Image Studio", layout="wide")
151
-
152
  st.title("🎨 Omni Image Studio")
153
 
154
- # Navigation
155
  page = st.radio(
156
  "Navigation",
157
  ["🖼️ Generieren", "✨ Bearbeiten", "🧪 Analyse", "📚 Galerie"],
@@ -165,153 +192,99 @@ st.session_state.page = page
165
  # GENERATE
166
  # ---------------------------
167
  if page == "🖼️ Generieren":
168
- prompt = st.text_area("Bildbeschreibung")
169
 
170
  if st.button("Generieren"):
171
- if prompt:
172
- status = st.empty()
173
- progress = st.progress(0)
174
-
175
- job = run_with_progress(generate_image, prompt)
176
 
177
- percent = 0
178
- while not job["done"]:
179
- percent = min(percent + 5, 95)
180
- progress.progress(percent)
181
- status.text(f"Generiere Bild... {percent}%")
182
- time.sleep(0.2)
183
 
184
- progress.progress(100)
185
- status.text("Fertig ✅")
186
-
187
- url = job["result"]
188
-
189
- if url:
190
- local_path = save_image_from_url(url)
191
-
192
- st.image(local_path)
193
- st.session_state.gallery.append({
194
- "path": local_path,
195
- "prompt": prompt
196
- })
197
 
198
  # ---------------------------
199
  # EDIT
200
  # ---------------------------
201
  elif page == "✨ Bearbeiten":
202
- st.subheader("✨ Bild bearbeiten")
203
-
204
  if st.session_state.selected_image:
205
  st.image(st.session_state.selected_image)
206
  input_image = st.session_state.selected_image
207
  else:
208
- uploaded = st.file_uploader("Bild hochladen")
209
- input_image = uploaded
210
 
211
- edit_prompt = st.text_area("Bearbeitung")
212
 
213
  if st.button("Bearbeiten"):
214
- if input_image and edit_prompt:
215
- status = st.empty()
216
- progress = st.progress(0)
217
-
218
- job = run_with_progress(edit_image, input_image, edit_prompt)
219
 
220
- percent = 0
221
- while not job["done"]:
222
- percent = min(percent + 5, 95)
223
- progress.progress(percent)
224
- status.text(f"Bearbeite Bild... {percent}%")
225
- time.sleep(0.2)
226
 
227
- progress.progress(100)
228
- status.text("Fertig ✅")
229
-
230
- url = job["result"]
231
-
232
- if url:
233
- local_path = save_image_from_url(url)
234
- st.image(local_path)
235
-
236
- st.session_state.gallery.append({
237
- "path": local_path,
238
- "prompt": edit_prompt
239
- })
240
 
241
  # ---------------------------
242
  # ANALYSE
243
  # ---------------------------
244
  elif page == "🧪 Analyse":
245
- st.subheader("🧪 Bild Analyse")
246
-
247
  if st.session_state.selected_image:
248
  st.image(st.session_state.selected_image)
249
  input_image = st.session_state.selected_image
250
  else:
251
- uploaded = st.file_uploader("Bild auswählen")
252
- input_image = uploaded
253
 
254
  if st.button("Analysieren"):
255
- if input_image:
256
- status = st.empty()
257
- progress = st.progress(0)
258
-
259
- job = run_with_progress(process_image, input_image)
260
 
261
- percent = 0
262
- while not job["done"]:
263
- percent = min(percent + 5, 95)
264
- progress.progress(percent)
265
- status.text(f"Analysiere Bild... {percent}%")
266
- time.sleep(0.2)
267
 
268
- progress.progress(100)
269
- status.text("Fertig ✅")
 
270
 
271
- result = job["result"]
272
-
273
- if isinstance(result, str) and result.startswith("http"):
274
- local_path = save_image_from_url(result)
275
- st.image(local_path)
276
-
277
- st.session_state.gallery.append({
278
- "path": local_path,
279
- "prompt": "Analyse"
280
- })
281
- else:
282
- st.write(result)
283
 
284
  # ---------------------------
285
  # GALLERY
286
  # ---------------------------
287
  elif page == "📚 Galerie":
288
- st.subheader("📸 Galerie")
289
-
290
  if not st.session_state.gallery:
291
- st.info("Keine Bilder vorhanden")
292
  else:
293
  cols = st.columns(3)
294
 
295
  for i, item in enumerate(st.session_state.gallery):
296
- path = item["path"]
297
- prompt = item["prompt"]
298
-
299
  with cols[i % 3]:
300
- st.image(path, caption=prompt)
301
 
302
- col1, col2 = st.columns(2)
303
 
304
- with col1:
305
- if st.button("✏️ Edit", key=f"edit_{i}"):
306
- st.session_state.selected_image = path
307
- st.session_state.page = "✨ Bearbeiten"
308
- st.rerun()
309
 
310
- with col2:
311
- if st.button("🧪 Analyse", key=f"proc_{i}"):
312
- st.session_state.selected_image = path
313
- st.session_state.page = "🧪 Analyse"
314
- st.rerun()
315
 
316
- if st.button("🗑️ Galerie leeren"):
317
  st.session_state.gallery = []
 
3
  import re
4
  import threading
5
  import time
 
6
  import requests
7
  import os
8
  import uuid
9
+ import tempfile
10
 
11
  # ---------------------------
12
+ # CONFIG
13
  # ---------------------------
14
  IMAGE_DIR = "data/images"
15
  os.makedirs(IMAGE_DIR, exist_ok=True)
16
 
 
 
 
17
  client_main = Client("selfit-camera/Omni-Image-Editor")
18
+ client_process = Client("SLSLK/n8")
19
 
20
  # ---------------------------
21
+ # SESSION
22
  # ---------------------------
23
  if "gallery" not in st.session_state:
24
  st.session_state.gallery = []
 
30
  st.session_state.page = "🖼️ Generieren"
31
 
32
  # ---------------------------
33
+ # HELPERS
34
  # ---------------------------
35
  def extract_url(html):
36
  match = re.search(r"src='([^']+)'", html)
 
41
  try:
42
  r = requests.get(url)
43
  if r.status_code != 200:
44
+ st.error(f"❌ Download Error HTTP {r.status_code}")
45
  return None
46
 
47
+ path = os.path.join(IMAGE_DIR, f"{uuid.uuid4()}.png")
 
 
48
  with open(path, "wb") as f:
49
  f.write(r.content)
50
 
51
  return path
 
52
  except Exception as e:
53
  st.error(f"❌ Save Error: {e}")
54
  return None
55
 
56
 
57
+ def upload_to_imgbb(file):
58
+ try:
59
+ api_key = os.getenv("IMGBB_API_KEY")
60
+ if not api_key:
61
+ st.error("❌ Missing IMGBB_API_KEY")
62
+ return None
63
 
64
+ res = requests.post(
65
+ "https://api.imgbb.com/1/upload",
66
+ data={"key": api_key},
67
+ files={"image": file.getvalue()}
68
+ )
69
+
70
+ if res.status_code == 200:
71
+ return res.json()["data"]["url"]
72
+ else:
73
+ st.error(f"❌ Upload Error HTTP {res.status_code}")
74
  return None
 
75
 
76
+ except Exception as e:
77
+ st.error(f"❌ Upload Exception: {e}")
78
+ return None
79
 
80
 
81
  # ---------------------------
 
96
 
97
  def edit_image(input_image, prompt):
98
  try:
99
+ if hasattr(input_image, "getvalue"):
100
+ image_url = upload_to_imgbb(input_image)
101
+
102
+ elif isinstance(input_image, str) and not input_image.startswith("http"):
103
+ with open(input_image, "rb") as f:
104
+ image_url = upload_to_imgbb(f)
105
+
106
+ else:
107
+ image_url = input_image
108
+
109
+ if not image_url:
110
  return None
111
 
112
  result = client_main.predict(
113
+ input_image=image_url,
114
  prompt=prompt,
115
  api_name="/edit_image_interface"
116
  )
 
124
 
125
  def process_image(input_image):
126
  try:
127
+ if hasattr(input_image, "getvalue"):
128
+ tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
129
+ tmp.write(input_image.getvalue())
130
+ tmp.close()
131
+ image_input = handle_file(tmp.name)
132
+ else:
133
+ image_input = handle_file(input_image)
134
 
135
  result = client_process.predict(
136
  image=image_input,
 
145
 
146
 
147
  # ---------------------------
148
+ # ASYNC
149
  # ---------------------------
150
+ def run_async(func, *args):
151
+ result = {"done": False, "data": None}
152
 
153
  def task():
154
+ result["data"] = func(*args)
155
+ result["done"] = True
156
 
157
  threading.Thread(target=task).start()
158
+ return result
159
+
160
+
161
+ def show_progress(job):
162
+ progress_bar = st.progress(0)
163
+
164
+ percent = 0
165
+ while not job["done"]:
166
+ percent += 5
167
+ if percent > 95:
168
+ percent = 95
169
+
170
+ progress_bar.progress(percent)
171
+ time.sleep(0.2)
172
+
173
+ progress_bar.progress(100)
174
 
175
 
176
  # ---------------------------
177
  # UI
178
  # ---------------------------
179
+ st.set_page_config(layout="wide")
 
180
  st.title("🎨 Omni Image Studio")
181
 
 
182
  page = st.radio(
183
  "Navigation",
184
  ["🖼️ Generieren", "✨ Bearbeiten", "🧪 Analyse", "📚 Galerie"],
 
192
  # GENERATE
193
  # ---------------------------
194
  if page == "🖼️ Generieren":
195
+ prompt = st.text_area("Prompt")
196
 
197
  if st.button("Generieren"):
198
+ job = run_async(generate_image, prompt)
199
+ show_progress(job)
 
 
 
200
 
201
+ url = job["data"]
202
+ if url:
203
+ path = save_image_from_url(url)
204
+ st.image(path)
 
 
205
 
206
+ st.session_state.gallery.append({
207
+ "path": path,
208
+ "prompt": prompt
209
+ })
 
 
 
 
 
 
 
 
 
210
 
211
  # ---------------------------
212
  # EDIT
213
  # ---------------------------
214
  elif page == "✨ Bearbeiten":
 
 
215
  if st.session_state.selected_image:
216
  st.image(st.session_state.selected_image)
217
  input_image = st.session_state.selected_image
218
  else:
219
+ input_image = st.file_uploader("Upload Image")
 
220
 
221
+ prompt = st.text_area("Edit Prompt")
222
 
223
  if st.button("Bearbeiten"):
224
+ job = run_async(edit_image, input_image, prompt)
225
+ show_progress(job)
 
 
 
226
 
227
+ url = job["data"]
228
+ if url:
229
+ path = save_image_from_url(url)
230
+ st.image(path)
 
 
231
 
232
+ st.session_state.gallery.append({
233
+ "path": path,
234
+ "prompt": prompt
235
+ })
 
 
 
 
 
 
 
 
 
236
 
237
  # ---------------------------
238
  # ANALYSE
239
  # ---------------------------
240
  elif page == "🧪 Analyse":
 
 
241
  if st.session_state.selected_image:
242
  st.image(st.session_state.selected_image)
243
  input_image = st.session_state.selected_image
244
  else:
245
+ input_image = st.file_uploader("Upload Image")
 
246
 
247
  if st.button("Analysieren"):
248
+ job = run_async(process_image, input_image)
249
+ show_progress(job)
 
 
 
250
 
251
+ result = job["data"]
 
 
 
 
 
252
 
253
+ if isinstance(result, str) and result.startswith("http"):
254
+ path = save_image_from_url(result)
255
+ st.image(path)
256
 
257
+ st.session_state.gallery.append({
258
+ "path": path,
259
+ "prompt": "Analyse"
260
+ })
261
+ else:
262
+ st.write(result)
 
 
 
 
 
 
263
 
264
  # ---------------------------
265
  # GALLERY
266
  # ---------------------------
267
  elif page == "📚 Galerie":
 
 
268
  if not st.session_state.gallery:
269
+ st.info("Keine Bilder")
270
  else:
271
  cols = st.columns(3)
272
 
273
  for i, item in enumerate(st.session_state.gallery):
 
 
 
274
  with cols[i % 3]:
275
+ st.image(item["path"], caption=item["prompt"])
276
 
277
+ c1, c2 = st.columns(2)
278
 
279
+ if c1.button("✏️ Edit", key=f"e{i}"):
280
+ st.session_state.selected_image = item["path"]
281
+ st.session_state.page = "✨ Bearbeiten"
282
+ st.rerun()
 
283
 
284
+ if c2.button("🧪 Analyse", key=f"a{i}"):
285
+ st.session_state.selected_image = item["path"]
286
+ st.session_state.page = "🧪 Analyse"
287
+ st.rerun()
 
288
 
289
+ if st.button("🗑️ Clear"):
290
  st.session_state.gallery = []