-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerator.py
More file actions
1250 lines (1053 loc) · 41.7 KB
/
generator.py
File metadata and controls
1250 lines (1053 loc) · 41.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Image generation/editing pipeline with pluggable API backends."""
import asyncio
import base64
from abc import ABC, abstractmethod
from typing import Optional
import aiohttp
import boto3
import config
import storage
# Edit prompts by category
EDIT_PROMPTS = {
"car_add_damage": "Add realistic moderate body damage to this car - major scratches or moderate dents on the body panels. Make the damage look natural and real, as if from a minor collision. Preserve existing photo style and lighting as much as possible.",
"delivery_proof": "In this existing photo, add a food delivery paper bag on the ground right in front of the door. The bag should be a small brown paper bag with a solid plain red sticker on the top keeping it closed. Preserve existing photo style and lighting as much as possible.",
"receipts": "Edit this receipt image to exactly double the total amount and all intermediate monetary values, including line item prices, subtotal, tax amount, total, and any other amount necessary. Keep everything else in the photo exactly the same.",
"product": "Edit this photo so this product looks like it arrived from the seller with a realistic issue that a customer would complain about. The issue can be either minor shipping damage (scuff/tear/rip/dent, paint chip, or a small crack) OR a manufacturing defect (uneven paint finish, misaligned seam, or a surface blemish). It still has to look like a real photo.",
}
class ImageGenerator(ABC):
"""Base class for image generation/editing APIs."""
name: str = "base"
generator_name: str = "base" # Used for DB storage
requires_presigned_url: bool = (
False # If True, needs S3 presigned URL instead of bytes
)
@abstractmethod
def edit(self, image_bytes: bytes, prompt: str) -> bytes:
"""Edit an image given raw bytes and a prompt. Returns edited image bytes."""
raise NotImplementedError
async def edit_async(
self,
image_bytes: bytes,
prompt: str,
session: aiohttp.ClientSession = None,
presigned_url: str = None,
) -> bytes:
"""Async version of edit. Override for async implementations."""
return self.edit(image_bytes, prompt)
class GrokGenerator(ImageGenerator):
"""Grok (xAI) image editing API."""
name = "grok-imagine-image-beta"
generator_name = "grok"
def __init__(self, api_key: str = None, model: str = "grok-imagine-image-beta"):
self.api_key = api_key or config.GROK_API_KEY
self.model = model
self.api_base = "https://api.x.ai/v1"
def edit(self, image_bytes: bytes, prompt: str) -> bytes:
"""Edit image using Grok API (sync version)."""
return asyncio.get_event_loop().run_until_complete(
self.edit_async(image_bytes, prompt)
)
async def edit_async(
self,
image_bytes: bytes,
prompt: str,
session: aiohttp.ClientSession = None,
presigned_url: str = None,
) -> bytes:
"""Edit image using Grok API (async version)."""
# Convert to base64 data URI
b64_data = base64.b64encode(image_bytes).decode("utf-8")
image_uri = f"data:image/jpeg;base64,{b64_data}"
url = f"{self.api_base}/images/edits"
payload = {
"prompt": prompt,
"image": {"url": image_uri},
"model": self.model,
}
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json",
}
close_session = False
if session is None:
session = aiohttp.ClientSession()
close_session = True
try:
async with session.post(
url,
json=payload,
headers=headers,
timeout=aiohttp.ClientTimeout(total=120),
) as response:
if response.status != 200:
text = await response.text()
raise RuntimeError(f"Grok API error {response.status}: {text}")
result = await response.json()
if "data" not in result or len(result["data"]) == 0:
raise RuntimeError(f"Unexpected Grok response: {result}")
img_data = result["data"][0]
if "b64_json" in img_data:
return base64.b64decode(img_data["b64_json"])
elif "url" in img_data:
async with session.get(
img_data["url"], timeout=aiohttp.ClientTimeout(total=60)
) as img_response:
if img_response.status != 200:
raise RuntimeError(f"Failed to download from {img_data['url']}")
return await img_response.read()
raise RuntimeError(f"No image data in response: {img_data}")
finally:
if close_session:
await session.close()
class QwenGenerator(ImageGenerator):
"""Qwen Image Edit via Fal AI API."""
name = "qwen-image-edit-2511"
generator_name = "qwen"
requires_presigned_url = True # Qwen needs image URLs, not raw bytes
def __init__(self, api_key: str = None):
self.api_key = api_key or config.FAL_API_KEY
self.api_url = "https://fal.run/fal-ai/qwen-image-edit-2511"
def edit(self, image_bytes: bytes, prompt: str) -> bytes:
"""Edit image using Qwen via Fal API (sync version)."""
return asyncio.get_event_loop().run_until_complete(
self.edit_async(image_bytes, prompt)
)
async def edit_async(
self,
image_bytes: bytes,
prompt: str,
session: aiohttp.ClientSession = None,
presigned_url: str = None,
) -> bytes:
"""Edit image using Qwen via Fal AI API (async version)."""
if not presigned_url:
raise RuntimeError("Qwen generator requires a presigned URL")
headers = {
"Authorization": f"Key {self.api_key}",
"Content-Type": "application/json",
}
payload = {
"prompt": prompt,
"image_urls": [presigned_url],
"num_inference_steps": 28,
"guidance_scale": 4.5,
"output_format": "png",
}
close_session = False
if session is None:
session = aiohttp.ClientSession()
close_session = True
try:
async with session.post(
self.api_url,
json=payload,
headers=headers,
timeout=aiohttp.ClientTimeout(total=180),
) as response:
if response.status != 200:
text = await response.text()
raise RuntimeError(f"Qwen/Fal API error {response.status}: {text}")
result = await response.json()
# Extract image URL from response
if "images" not in result or len(result["images"]) == 0:
raise RuntimeError(f"Unexpected Qwen response: {result}")
image_url = result["images"][0]["url"]
# Download the generated image
async with session.get(
image_url, timeout=aiohttp.ClientTimeout(total=60)
) as img_response:
if img_response.status != 200:
raise RuntimeError(f"Failed to download from {image_url}")
return await img_response.read()
finally:
if close_session:
await session.close()
class SeedreamGenerator(ImageGenerator):
"""Seedream v4.5 Image Edit via Fal AI API (ByteDance)."""
name = "seedream-v4.5-1k"
generator_name = "seedream"
requires_presigned_url = True # Seedream needs image URLs, not raw bytes
def __init__(self, api_key: str = None):
self.api_key = api_key or config.FAL_API_KEY
self.api_url = "https://fal.run/fal-ai/bytedance/seedream/v4.5/edit"
def edit(self, image_bytes: bytes, prompt: str) -> bytes:
"""Edit image using Seedream via Fal API (sync version)."""
return asyncio.get_event_loop().run_until_complete(
self.edit_async(image_bytes, prompt)
)
async def edit_async(
self,
image_bytes: bytes,
prompt: str,
session: aiohttp.ClientSession = None,
presigned_url: str = None,
) -> bytes:
"""Edit image using Seedream via Fal AI API (async version)."""
if not presigned_url:
raise RuntimeError("Seedream generator requires a presigned URL")
headers = {
"Authorization": f"Key {self.api_key}",
"Content-Type": "application/json",
}
payload = {
"prompt": prompt,
"image_urls": [presigned_url],
"image_size": {
"width": 1024,
"height": 1024,
},
"seed": config.SEED,
}
close_session = False
if session is None:
session = aiohttp.ClientSession()
close_session = True
try:
async with session.post(
self.api_url,
json=payload,
headers=headers,
timeout=aiohttp.ClientTimeout(total=180),
) as response:
if response.status != 200:
text = await response.text()
raise RuntimeError(
f"Seedream/Fal API error {response.status}: {text}"
)
result = await response.json()
# Extract image URL from response
if "images" not in result or len(result["images"]) == 0:
raise RuntimeError(f"Unexpected Seedream response: {result}")
image_url = result["images"][0]["url"]
# Download the generated image
async with session.get(
image_url, timeout=aiohttp.ClientTimeout(total=60)
) as img_response:
if img_response.status != 200:
raise RuntimeError(f"Failed to download from {image_url}")
return await img_response.read()
finally:
if close_session:
await session.close()
class OpenAIGenerator(ImageGenerator):
"""GPT Image 1.5 via Fal AI API."""
name = "gpt-image-1.5"
generator_name = "openai"
requires_presigned_url = True # Fal needs image URLs, not raw bytes
def __init__(self, api_key: str = None):
self.api_key = api_key or config.FAL_API_KEY
self.api_url = "https://fal.run/fal-ai/gpt-image-1.5"
def edit(self, image_bytes: bytes, prompt: str) -> bytes:
"""Edit image using GPT Image 1.5 via Fal API (sync version)."""
return asyncio.get_event_loop().run_until_complete(
self.edit_async(image_bytes, prompt)
)
async def edit_async(
self,
image_bytes: bytes,
prompt: str,
session: aiohttp.ClientSession = None,
presigned_url: str = None,
) -> bytes:
"""Edit image using GPT Image 1.5 via Fal API (async version)."""
if not presigned_url:
raise RuntimeError("OpenAI/GPT Image generator requires a presigned URL")
headers = {
"Authorization": f"Key {self.api_key}",
"Content-Type": "application/json",
}
payload = {
"prompt": prompt,
"image_urls": [presigned_url],
"image_size": "1024x1024",
"quality": "high",
"input_fidelity": "high",
"output_format": "png",
}
close_session = False
if session is None:
session = aiohttp.ClientSession()
close_session = True
try:
async with session.post(
f"{self.api_url}/edit",
json=payload,
headers=headers,
timeout=aiohttp.ClientTimeout(total=180),
) as response:
if response.status != 200:
text = await response.text()
raise RuntimeError(
f"GPT Image/Fal API error {response.status}: {text}"
)
result = await response.json()
# Extract image URL from response
if "images" not in result or len(result["images"]) == 0:
raise RuntimeError(f"Unexpected GPT Image response: {result}")
image_url = result["images"][0]["url"]
# Download the generated image
async with session.get(
image_url, timeout=aiohttp.ClientTimeout(total=60)
) as img_response:
if img_response.status != 200:
raise RuntimeError(f"Failed to download from {image_url}")
return await img_response.read()
finally:
if close_session:
await session.close()
async def generate_async(
self, prompt: str, session: aiohttp.ClientSession = None
) -> bytes:
"""Generate image from text prompt only (text-to-image)."""
headers = {
"Authorization": f"Key {self.api_key}",
"Content-Type": "application/json",
}
payload = {
"prompt": prompt,
"image_size": "1024x1024",
"quality": "high",
"output_format": "png",
}
close_session = False
if session is None:
session = aiohttp.ClientSession()
close_session = True
try:
async with session.post(
self.api_url,
json=payload,
headers=headers,
timeout=aiohttp.ClientTimeout(total=180),
) as response:
if response.status != 200:
text = await response.text()
raise RuntimeError(
f"GPT Image/Fal API error {response.status}: {text}"
)
result = await response.json()
# Extract image URL from response
if "images" not in result or len(result["images"]) == 0:
raise RuntimeError(f"Unexpected GPT Image response: {result}")
image_url = result["images"][0]["url"]
# Download the generated image
async with session.get(
image_url, timeout=aiohttp.ClientTimeout(total=60)
) as img_response:
if img_response.status != 200:
raise RuntimeError(f"Failed to download from {image_url}")
return await img_response.read()
finally:
if close_session:
await session.close()
class GeminiGenerator(ImageGenerator):
"""Google Gemini image generation/editing API (Nano Banana Pro / Imagen 3)."""
name = "gemini-3-pro-image-preview"
generator_name = "gemini"
def __init__(self, api_key: str = None, model: str = "gemini-3-pro-image-preview"):
self.api_key = api_key or config.GEMINI_API_KEY
self.model = model
self.name = model # Update name to match model
self.api_base = "https://generativelanguage.googleapis.com/v1beta"
def edit(self, image_bytes: bytes, prompt: str) -> bytes:
"""Edit image using Gemini API (sync version)."""
return asyncio.get_event_loop().run_until_complete(
self.edit_async(image_bytes, prompt)
)
async def edit_async(
self,
image_bytes: bytes,
prompt: str,
session: aiohttp.ClientSession = None,
presigned_url: str = None,
) -> bytes:
"""Edit image using Gemini API (async version).
Sends the image + prompt and requests an edited image output.
"""
# Convert image to base64
b64_data = base64.b64encode(image_bytes).decode("utf-8")
# Detect mime type from bytes
mime_type = "image/jpeg"
if image_bytes[:8] == b"\x89PNG\r\n\x1a\n":
mime_type = "image/png"
elif image_bytes[:2] == b"\xff\xd8":
mime_type = "image/jpeg"
url = f"{self.api_base}/models/{self.model}:generateContent"
payload = {
"contents": [
{
"parts": [
{"text": prompt},
{"inline_data": {"mime_type": mime_type, "data": b64_data}},
]
}
],
"generationConfig": {"responseModalities": ["Image"]},
}
headers = {
"x-goog-api-key": self.api_key,
"Content-Type": "application/json",
}
close_session = False
if session is None:
session = aiohttp.ClientSession()
close_session = True
try:
async with session.post(
url,
json=payload,
headers=headers,
timeout=aiohttp.ClientTimeout(total=180),
) as response:
if response.status != 200:
text = await response.text()
raise RuntimeError(f"Gemini API error {response.status}: {text}")
result = await response.json()
# Extract image from response
if "candidates" not in result or len(result["candidates"]) == 0:
raise RuntimeError(f"No candidates in Gemini response: {result}")
candidate = result["candidates"][0]
if "content" not in candidate or "parts" not in candidate["content"]:
raise RuntimeError(f"No content parts in Gemini response: {candidate}")
# Find the image part in the response (API returns camelCase)
for part in candidate["content"]["parts"]:
# Check both camelCase (API response) and snake_case (docs)
if "inlineData" in part:
img_data = part["inlineData"]
return base64.b64decode(img_data["data"])
elif "inline_data" in part:
img_data = part["inline_data"]
return base64.b64decode(img_data["data"])
raise RuntimeError(
f"No image found in Gemini response parts: {candidate['content']['parts']}"
)
finally:
if close_session:
await session.close()
async def generate_async(
self, prompt: str, session: aiohttp.ClientSession = None
) -> bytes:
"""Generate image from text prompt only (text-to-image)."""
url = f"{self.api_base}/models/{self.model}:generateContent"
payload = {
"contents": [{"parts": [{"text": prompt}]}],
"generationConfig": {"responseModalities": ["Image"]},
}
headers = {
"x-goog-api-key": self.api_key,
"Content-Type": "application/json",
}
close_session = False
if session is None:
session = aiohttp.ClientSession()
close_session = True
try:
async with session.post(
url,
json=payload,
headers=headers,
timeout=aiohttp.ClientTimeout(total=180),
) as response:
if response.status != 200:
text = await response.text()
raise RuntimeError(f"Gemini API error {response.status}: {text}")
result = await response.json()
# Extract image from response
if "candidates" not in result or len(result["candidates"]) == 0:
raise RuntimeError(f"No candidates in Gemini response: {result}")
candidate = result["candidates"][0]
if "content" not in candidate or "parts" not in candidate["content"]:
raise RuntimeError(f"No content parts in Gemini response: {candidate}")
# Find the image part in the response (API returns camelCase)
for part in candidate["content"]["parts"]:
# Check both camelCase (API response) and snake_case (docs)
if "inlineData" in part:
img_data = part["inlineData"]
return base64.b64decode(img_data["data"])
elif "inline_data" in part:
img_data = part["inline_data"]
return base64.b64decode(img_data["data"])
raise RuntimeError(
f"No image found in Gemini response parts: {candidate['content']['parts']}"
)
finally:
if close_session:
await session.close()
class GeminiFalGenerator(ImageGenerator):
"""Google Gemini via Fal.ai (nano-banana-pro model). Same output as GeminiGenerator."""
name = "gemini-3-pro-image-preview" # Same as direct Gemini
generator_name = "gemini" # Same as direct Gemini
requires_presigned_url = True # Fal needs image URLs
def __init__(self, api_key: str = None):
self.api_key = api_key or config.FAL_API_KEY
self.api_url = "https://fal.run/fal-ai/nano-banana-pro/edit"
def edit(self, image_bytes: bytes, prompt: str) -> bytes:
"""Edit image using Fal API (sync version)."""
return asyncio.get_event_loop().run_until_complete(
self.edit_async(image_bytes, prompt)
)
async def edit_async(
self,
image_bytes: bytes,
prompt: str,
session: aiohttp.ClientSession = None,
presigned_url: str = None,
) -> bytes:
"""Edit image using Fal API (async version)."""
if not presigned_url:
raise RuntimeError("GeminiFal generator requires a presigned URL")
headers = {
"Authorization": f"Key {self.api_key}",
"Content-Type": "application/json",
}
payload = {
"prompt": prompt,
"image_urls": [presigned_url],
}
close_session = False
if session is None:
session = aiohttp.ClientSession()
close_session = True
try:
async with session.post(
self.api_url,
json=payload,
headers=headers,
timeout=aiohttp.ClientTimeout(total=300),
) as response:
if response.status != 200:
text = await response.text()
raise RuntimeError(f"Fal API error {response.status}: {text}")
result = await response.json()
if "images" not in result or len(result["images"]) == 0:
raise RuntimeError(f"Unexpected Fal response: {result}")
image_url = result["images"][0]["url"]
async with session.get(
image_url, timeout=aiohttp.ClientTimeout(total=60)
) as img_resp:
if img_resp.status != 200:
raise RuntimeError(f"Failed to download from {image_url}")
return await img_resp.read()
finally:
if close_session:
await session.close()
async def generate_async(
self, prompt: str, session: aiohttp.ClientSession = None
) -> bytes:
"""Generate image from text prompt only (text-to-image)."""
headers = {
"Authorization": f"Key {self.api_key}",
"Content-Type": "application/json",
}
payload = {
"prompt": prompt,
}
close_session = False
if session is None:
session = aiohttp.ClientSession()
close_session = True
try:
# Use the non-edit endpoint for text-to-image
t2i_url = "https://fal.run/fal-ai/nano-banana-pro"
async with session.post(
t2i_url,
json=payload,
headers=headers,
timeout=aiohttp.ClientTimeout(total=300),
) as response:
if response.status != 200:
text = await response.text()
raise RuntimeError(f"Fal API error {response.status}: {text}")
result = await response.json()
if "images" not in result or len(result["images"]) == 0:
raise RuntimeError(f"Unexpected Fal response: {result}")
image_url = result["images"][0]["url"]
async with session.get(
image_url, timeout=aiohttp.ClientTimeout(total=60)
) as img_resp:
if img_resp.status != 200:
raise RuntimeError(f"Failed to download from {image_url}")
return await img_resp.read()
finally:
if close_session:
await session.close()
class GeminiReplicateGenerator(ImageGenerator):
"""Google Gemini via Replicate (nano-banana-pro model). Same output as GeminiGenerator."""
name = "gemini-3-pro-image-preview" # Same as direct Gemini
generator_name = "gemini" # Same as direct Gemini
def __init__(self, api_token: str = None, model: str = "google/nano-banana-pro"):
self.api_token = api_token or config.REPLICATE_API_TOKEN
self.model = model
self.api_base = "https://api.replicate.com/v1"
def edit(self, image_bytes: bytes, prompt: str) -> bytes:
"""Edit image using Replicate API (sync version)."""
return asyncio.get_event_loop().run_until_complete(
self.edit_async(image_bytes, prompt)
)
async def edit_async(
self,
image_bytes: bytes,
prompt: str,
session: aiohttp.ClientSession = None,
presigned_url: str = None,
) -> bytes:
"""Edit image using Replicate API (async version)."""
b64_data = base64.b64encode(image_bytes).decode("utf-8")
mime_type = (
"image/png" if image_bytes[:8] == b"\x89PNG\r\n\x1a\n" else "image/jpeg"
)
data_uri = f"data:{mime_type};base64,{b64_data}"
headers = {
"Authorization": f"Bearer {self.api_token}",
"Content-Type": "application/json",
}
payload = {
"input": {
"prompt": prompt,
"image_input": [data_uri],
"resolution": "2K",
"output_format": "jpg",
}
}
close_session = False
if session is None:
session = aiohttp.ClientSession()
close_session = True
try:
# Create prediction and wait for result
async with session.post(
f"{self.api_base}/models/{self.model}/predictions",
json=payload,
headers=headers,
timeout=aiohttp.ClientTimeout(total=300),
) as response:
if response.status not in (200, 201):
text = await response.text()
raise RuntimeError(f"Replicate API error {response.status}: {text}")
result = await response.json()
# If not completed, poll for result
if result.get("status") not in ("succeeded", "failed", "canceled"):
poll_url = (
result.get("urls", {}).get("get")
or f"{self.api_base}/predictions/{result['id']}"
)
for _ in range(120): # Max 2 minutes polling
await asyncio.sleep(1)
async with session.get(poll_url, headers=headers) as poll_resp:
result = await poll_resp.json()
if result.get("status") in ("succeeded", "failed", "canceled"):
break
if result.get("status") != "succeeded":
raise RuntimeError(f"Replicate prediction failed: {result}")
# Download the output image
output_url = result.get("output")
if isinstance(output_url, list):
output_url = output_url[0] if output_url else None
if not output_url:
raise RuntimeError(f"No output URL in Replicate response: {result}")
async with session.get(output_url) as img_resp:
return await img_resp.read()
finally:
if close_session:
await session.close()
async def generate_async(
self, prompt: str, session: aiohttp.ClientSession = None
) -> bytes:
"""Generate image from text prompt only (text-to-image)."""
headers = {
"Authorization": f"Bearer {self.api_token}",
"Content-Type": "application/json",
}
payload = {
"input": {
"prompt": prompt,
"resolution": "2K",
"output_format": "jpg",
}
}
close_session = False
if session is None:
session = aiohttp.ClientSession()
close_session = True
try:
async with session.post(
f"{self.api_base}/models/{self.model}/predictions",
json=payload,
headers=headers,
timeout=aiohttp.ClientTimeout(total=300),
) as response:
if response.status not in (200, 201):
text = await response.text()
raise RuntimeError(f"Replicate API error {response.status}: {text}")
result = await response.json()
if result.get("status") not in ("succeeded", "failed", "canceled"):
poll_url = (
result.get("urls", {}).get("get")
or f"{self.api_base}/predictions/{result['id']}"
)
for _ in range(120):
await asyncio.sleep(1)
async with session.get(poll_url, headers=headers) as poll_resp:
result = await poll_resp.json()
if result.get("status") in ("succeeded", "failed", "canceled"):
break
if result.get("status") != "succeeded":
raise RuntimeError(f"Replicate prediction failed: {result}")
output_url = result.get("output")
if isinstance(output_url, list):
output_url = output_url[0] if output_url else None
if not output_url:
raise RuntimeError(f"No output URL in Replicate response: {result}")
async with session.get(output_url) as img_resp:
return await img_resp.read()
finally:
if close_session:
await session.close()
# Registry of available generators
GENERATORS = {
"grok": GrokGenerator,
"qwen": QwenGenerator,
"seedream": SeedreamGenerator,
"openai": OpenAIGenerator,
"gemini": GeminiGenerator,
"gemini-fal": GeminiFalGenerator,
"gemini-replicate": GeminiReplicateGenerator,
}
def get_generator(name: str, **kwargs) -> ImageGenerator:
"""Get a generator instance by name."""
if name not in GENERATORS:
raise ValueError(
f"Unknown generator: {name}. Available: {list(GENERATORS.keys())}"
)
return GENERATORS[name](**kwargs)
def process_image(
image_id: str,
generator: ImageGenerator,
s3_client=None,
dry_run: bool = False,
) -> Optional[str]:
"""Process a single image: download from S3, edit, upload result, update DB.
Returns the S3 path of the generated image, or None on failure.
"""
# Get image metadata from DB
img = storage.get_image_by_id(image_id)
if not img:
print(f" Image not found in DB: {image_id}")
return None
category = img["category"]
source = img["source"]
s3_processed_path = img.get("s3_processed_path")
if not s3_processed_path:
print(f" No S3 path for image: {image_id}")
return None
# Get prompt for category
prompt = EDIT_PROMPTS.get(category)
if not prompt:
print(f" No prompt for category: {category}")
return None
# Initialize S3 client if needed
if s3_client is None:
s3_client = boto3.client("s3", region_name=config.S3_REGION)
# Parse S3 path
if s3_processed_path.startswith("s3://"):
# Full S3 URI
parts = s3_processed_path.replace("s3://", "").split("/", 1)
bucket = parts[0]
key = parts[1]
else:
# Relative path - assume it's under our bucket
bucket = config.S3_BUCKET
key = s3_processed_path.lstrip("/")
# Handle local-style paths like "data/processed/..."
if key.startswith("data/"):
key = key[5:] # Remove "data/" prefix
print(f" Downloading from s3://{bucket}/{key}")
if dry_run:
print(f" [DRY RUN] Would process {image_id}")
return "DRY_RUN"
image_bytes = None
presigned_url = None
if generator.requires_presigned_url:
# Generate presigned URL for generators that need it (e.g., Qwen)
try:
presigned_url = s3_client.generate_presigned_url(
"get_object",
Params={"Bucket": bucket, "Key": key},
ExpiresIn=300,
)
except Exception as e:
print(f" Presigned URL failed: {e}")
return None
else:
# Download image from S3
try:
response = s3_client.get_object(Bucket=bucket, Key=key)
image_bytes = response["Body"].read()
except Exception as e:
print(f" Failed to download: {e}")
return None
# Edit image (use async version via asyncio.run for presigned_url support)
print(f" Sending to {generator.name}...")
try:
edited_bytes = asyncio.get_event_loop().run_until_complete(
generator.edit_async(image_bytes, prompt, presigned_url=presigned_url)
)
except Exception as e:
print(f" Generation failed: {e}")
return None
# Upload to S3
output_key = f"generated/{category}/{generator.name}/{source}/{image_id}_edited.png"
output_s3_path = f"s3://{config.S3_BUCKET}/{output_key}"
print(f" Uploading to {output_s3_path}")
try:
s3_client.put_object(
Bucket=config.S3_BUCKET,
Key=output_key,
Body=edited_bytes,
ContentType="image/png",
)
except Exception as e:
print(f" Failed to upload: {e}")
return None
# Update DB - insert into generated_images table
storage.insert_generated_image(
base_image_id=image_id,
generator=generator.generator_name,
model=generator.name,
s3_path=output_s3_path,
prompt=prompt,
)
return output_s3_path
async def process_image_async(
image_id: str,
generator: ImageGenerator,
s3_client,
session: aiohttp.ClientSession,
dry_run: bool = False,
) -> Optional[str]:
"""Process a single image asynchronously."""
# Get image metadata from DB
img = storage.get_image_by_id(image_id)
if not img:
return None
category = img["category"]
source = img["source"]
s3_processed_path = img.get("s3_processed_path")