-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfastapi_server.py
More file actions
493 lines (390 loc) · 22.1 KB
/
fastapi_server.py
File metadata and controls
493 lines (390 loc) · 22.1 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
from config import * # import all variables and core functions
from fastapi import FastAPI, UploadFile, File , Form , HTTPException
from fastapi.responses import JSONResponse
import base64
import json
app = FastAPI()
# =================================================================================================
# Model: gemini-vision-pro
# Task: Visual Q&A
# function: answers any question from image(s) input(s)
# =================================================================================================
@app.post("/image_to_text/gemini_vision")
async def image_to_text_gemini_vision(images: UploadFile = File(...),prompt: str = Form(...),role : str = File(...)):
try:
data = {"prompt":prompt,"role":role}
result = await core.gemini_img2txt(data,images)
return JSONResponse(content={"status":"success","result":result})
except Exception as e:
raise HTTPException(status_code=500,detail={"status":"error","message":str(e)})
# =================================================================================================
# Model: gemini-pro
# Task: All NLP tasks
# function: Chatgpt alternative
# =================================================================================================
@app.post("/text_generation/gemini")
async def text_generation(role: str = Form(...),prompt: str = Form(...)):
try:
result = core.text_generation(role,prompt)
return JSONResponse(content={"status":"success","result":result})
except Exception as e:
raise HTTPException(status_code=500,detail={"status":"error","message":str(e)})
# =================================================================================================
# Model: ssd-1b-anime
# Task: text to image
# function: generates anime images from text input
# =================================================================================================
@app.post("/text_to_image/ssd_1b_anime")
async def text_to_image_ssd_1b_anime(prompt: str = Form(...)):
try:
image_bytes = core.text2image(prompt, txt2img_SDD_1B_ANIME_api_token)
if MODEL_LOADING_MESSAGE.encode() in image_bytes:
raise HTTPException(status_code=401, detail=MODEL_LOADING_MESSAGE)
result = base64.b64encode(image_bytes).decode("utf-8")
return JSONResponse(content={"status": "success", "result": result})
except Exception as e:
raise HTTPException(status_code=500, detail={"status": "error", "message": str(e)})
# =================================================================================================
# Model : SSD_1B (Base Model)
# Speciality: Base Model
# Prompt : {"prompt":"NEON CAT"}
# =================================================================================================
@app.post("/txt2img/SSD_1B")
async def text2image_SSD_1B(prompt: str):
try:
image_bytes = core.text2image({"inputs": prompt}, txt2img_SDD_1B_api_token)
base64_encoded_image = base64.b64encode(image_bytes).decode('utf-8')
return JSONResponse(content={"status": "success", "image": base64_encoded_image})
except Exception as e:
raise HTTPException(status_code=500, detail={"status": "error", "message": str(e)})
# =================================================================================================
# Model : OPENDALLE-V1 (Base Model)
# Speciality: Base Model
# Prompt : {"prompt":"NEON CAT"}
# =================================================================================================
@app.post("/txt2img/OPENDALLE")
async def text2image_OPENDALLE(prompt: str):
try:
image_bytes = core.text2image({"inputs": prompt}, txt2img_OPENDALLE_api_token)
base64_encoded_image = base64.b64encode(image_bytes).decode('utf-8')
return JSONResponse(content={"status": "success", "image": base64_encoded_image})
except Exception as e:
raise HTTPException(status_code=500, detail={"status": "error", "message": str(e)})
# =================================================================================================
# Model : OPENDALLE-V1 (EXAMPLE)
# Speciality: Generates Content based on this prompt: Ultra Realistic, Neon Lightning , 16K, Face Focus , Anime Picture , Smooth Lightning
# Prompt : {"prompt":"NEON CAT"}
# =================================================================================================
@app.post("/txt2img/OPENDALLE/Speciality")
async def text2image_OPENDALLE_Speciality_1(prompt: str):
try:
image_bytes = core.text2image({"inputs": prompt}, txt2img_OPENDALLE_api_token)
base64_encoded_image = base64.b64encode(image_bytes).decode('utf-8')
return JSONResponse(content={"status": "success", "image": base64_encoded_image})
except Exception as e:
raise HTTPException(status_code=500, detail={"status": "error", "message": str(e)})
# =================================================================================================
# Model : BLIP_IMAGE_CAPTIONING_LARGE
# Speciality: Base Model
# prompt : {"file":file}
# =================================================================================================
@app.post('/img2txt/BLIP_IMAGE_CAPTIONING_LARGE')
async def image2text_BLIP(file: UploadFile = File(...)):
try:
data = await file.read()
result = core.image2text(data, img2txt_BLIP_api_token)
return JSONResponse(content={"status": "success", "text": result[0]["generated_text"]})
except Exception as e:
raise HTTPException(status_code=500, detail={"status": "error", "message": str(e)})
# =================================================================================================
# Model : BLIP_IMAGE_CAPTIONING_LARGE
# Speciality: Base Model
# prompt : {"file":file}
# =================================================================================================
@app.post('/audio2txt/WHISPER_LARGE_V2')
async def audio2text_WHISPER(file: UploadFile = File(...)):
try:
data = await file.read()
output = core.audio2text(data)
return JSONResponse(content={"status": "success", "text": output})
except Exception as e:
raise HTTPException(status_code=500, detail={"status": "error", "message": str(e)})
# =================================================================================================
# Model : MMS_TTS_ENGs
# Speciality: Base Model
# prompt : {"prompt":"hello world!"}
# =================================================================================================
@app.post('/txt2audio/MMS_TTS_ENG')
async def text2audio_MMS_TSS_ENG(data: dict):
try:
text_input = data.get('prompt')
audio_bytes = core.text2audio(text_input, txt2audio_MMS_TTS_ENG_api_token)
return JSONResponse(content={'audio': base64.b64encode(audio_bytes).decode('utf-8')})
except Exception as e:
raise HTTPException(status_code=500, detail={'status': 'error', 'message': str(e)})
# =================================================================================================
# IMAGE TO AUDIO
# =================================================================================================
def query_huggingface_api(data):
response = requests.post(img2txt_BLIP_api_token, headers=headers, data=data)
return response.json()
@app.post('/img2audio/MMS_BLIP')
async def image2audio_MMS_BLIP(file: UploadFile = File(...)):
try:
data = await file.read()
result = query_huggingface_api(data)
audio_bytes = core.text2audio(result[0]["generated_text"], txt2audio_MMS_TTS_ENG_api_token)
audio_base64 = base64.b64encode(audio_bytes).decode('utf-8')
return JSONResponse(content={"status": "success", "audio": audio_base64}, status_code=200)
except Exception as e:
raise HTTPException(status_code=500, detail={"status": "error", "message": str(e)})
# =================================================================================================
# AUDIO TO IMAGE
# =================================================================================================
@app.post('/audio2img/WHISPER_OPENDALLE')
async def audio2img_WHISPER_OPENDALLE(file: UploadFile = File(...)):
try:
text = core.audio2text(await file.read())
image_bytes = core.text2image({
"inputs": text,
}, txt2img_OPENDALLE_api_token)
base64_encoded_image = base64.b64encode(image_bytes).decode('utf-8')
return JSONResponse(content={"status": "success", "Image": base64_encoded_image}, status_code=200)
except Exception as e:
raise HTTPException(status_code=500, detail={"status": "error", "message": str(e)})
@app.post('/audio2img/WHISPER_SSD_1B')
async def audio2img_WHISPER_SSD_1B(file: UploadFile = File(...)):
try:
text = core.audio2text(await file.read())
image_bytes = core.text2image({
"inputs": text,
}, txt2img_SDD_1B_api_token)
base64_encoded_image = base64.b64encode(image_bytes).decode('utf-8')
return JSONResponse(content={"status": "success", "Image": base64_encoded_image}, status_code=200)
except Exception as e:
raise HTTPException(status_code=500, detail={"status": "error", "message": str(e)})
@app.post('/audio2img/WHISPER_SSD_1B_ANIME')
async def audio2img_WHISPER_SSD_1B_ANIME(file: UploadFile = File(...)):
try:
text = core.audio2text(await file.read())
image_bytes = core.text2image({
"inputs": text,
}, txt2img_SDD_1B_ANIME_api_token)
base64_encoded_image = base64.b64encode(image_bytes).decode('utf-8')
return JSONResponse(content={"status": "success", "Image": base64_encoded_image}, status_code=200)
except Exception as e:
raise HTTPException(status_code=500, detail={"status": "error", "message": str(e)})
# =================================================================================================
# IMAGE CLASSIFICATION
# =================================================================================================
@app.post('/image_classification/RESNET')
async def image_classification_RESNET(file: UploadFile = File(...)):
try:
image = await file.read()
result = core.image_classification(image, img_classification_RESNET_api_token)
parsed_result = json.loads(result)
return JSONResponse(content={"status": "success", "classes": parsed_result}, status_code=200)
except Exception as e:
raise HTTPException(status_code=500, detail={"status": "error", "message": str(e)})
@app.post('/image_classification/VIT_AGE')
async def image_classification_VIT_AGE(file: UploadFile = File(...)):
try:
image = await file.read()
result = core.image_classification(image, img_classification_VIT_AGE_api_token)
parsed_result = json.loads(result)
return JSONResponse(content={"status": "success", "classes": parsed_result}, status_code=200)
except Exception as e:
raise HTTPException(status_code=500, detail={"status": "error", "message": str(e)})
# =================================================================================================
# IMAGE CLASSIFICATION - NFWS
# =================================================================================================
@app.post('/image_classification/NFWS')
async def image_classification_NFWS(file: UploadFile = File(...)):
try:
image = await file.read()
result = core.image_classification(image, img_classification_NFWS_api_token)
parsed_result = json.loads(result)
return JSONResponse(content={"status": "success", "classes": parsed_result}, status_code=200)
except Exception as e:
raise HTTPException(status_code=500, detail={"status": "error", "message": str(e)})
# =================================================================================================
# IMAGE SEGMENTATION - B2_CLOTHES
# =================================================================================================
@app.post("/image_segmentation/B2_CLOTHES")
async def image_segmentation_B2_CLOTHES(file: UploadFile = File(...)):
try:
data = await file.read()
image_bytes = core.image_segmentation(data, img_segmentation_b2_clothes_api_token)
# Parse the JSON string into a Python list of dictionaries
data_list = json.loads(image_bytes)
scores = []
labels = []
segmented_pictures = []
for obj in data_list:
score = obj['score']
label = obj['label']
mask_base64 = obj['mask']
# DO APPEND STUFF :D
scores.append(score)
labels.append(label)
segmented_pictures.append(mask_base64)
return JSONResponse(content={"status": "success", "Segmented Image": {"labels": labels, "scores": scores,
"segmented_pictures": segmented_pictures}},
status_code=200)
except Exception as e:
raise HTTPException(status_code=500, detail={"status": "error", "message": str(e)})
# =================================================================================================
# AUDIO CLASSIFICATION - Hubert_emotion
# =================================================================================================
@app.post('/image_classification/Hubert_emotion')
async def audio_classification_Hubert_emotion(file: UploadFile = File(...)):
try:
data = core.audio_classification(await file.read(), audio_classification_Hubert_emotion_api_token)
list_data = json.loads(data)
scores = []
labels = []
for obj in list_data:
scores.append(obj["score"])
labels.append(obj["label"])
return JSONResponse(content={"status": "success", "result": {"scores": scores, "labels": labels}}, status_code=200)
except Exception as e:
raise HTTPException(status_code=500, detail={"status": "error", "message": str(e)})
# =================================================================================================
# AUDIO CLASSIFICATION - wav2vec2_lg_xlsr_en
# =================================================================================================
@app.post('/image_classification/wav2vec2_lg_xlsr_en')
async def audio_classification_wav2vec2_lg_xlsr_en(file: UploadFile = File(...)):
try:
data = core.audio_classification(await file.read(), audio_classification_wav2vec2_lg_xlsr_en_api_token)
list_data = json.loads(data)
scores = []
labels = []
for obj in list_data:
scores.append(obj["score"])
labels.append(obj["label"])
return JSONResponse(content={"status": "success", "result": {"scores": scores, "labels": labels}}, status_code=200)
except Exception as e:
raise HTTPException(status_code=500, detail={"status": "error", "message": str(e)})
# =================================================================================================
# AUDIO CLASSIFICATION - distil_ast_audioset
# =================================================================================================
@app.post('/image_classification/distil_ast_audioset')
async def audio_classification_distil_ast_audioset(file: UploadFile = File(...)):
try:
data = core.audio_classification(await file.read(), audio_classification_distil_ast_audioset_api_token)
list_data = json.loads(data)
scores = []
labels = []
for obj in list_data:
scores.append(obj["score"])
labels.append(obj["label"])
return JSONResponse(content={"status": "success", "result": {"scores": scores, "labels": labels}}, status_code=200)
except Exception as e:
raise HTTPException(status_code=500, detail={"status": "error", "message": str(e)})
# =================================================================================================
# IMAGE CLASSIFICATION - wav2vec2_large_xlsr_53_gender
# =================================================================================================
@app.post('/image_classification/wav2vec2_large_xlsr_53_gender')
async def audio_classification_wav2vec2_large_xlsr_53_gender(file: UploadFile = File(...)):
try:
data = core.audio_classification(await file.read(), audio_classification_wav2vec2_large_xlsr_53_gender_api_token)
list_data = json.loads(data)
scores = []
labels = []
for obj in list_data:
scores.append(obj["score"])
labels.append(obj["label"])
return JSONResponse(content={"status": "success", "result": {"scores": scores, "labels": labels}}, status_code=200)
except Exception as e:
raise HTTPException(status_code=500, detail={"status": "error", "message": str(e)})
# =================================================================================================
# IMAGE CLASSIFICATION - mms_lid_126
# =================================================================================================
@app.post('/image_classification/mms_lid_126')
async def audio_classification_mms_lid_126(file: UploadFile = File(...)):
try:
data = core.audio_classification(await file.read(), audio_classification_mms_lid_126_api_token)
list_data = json.loads(data)
scores = []
labels = []
for obj in list_data:
scores.append(obj["score"])
labels.append(obj["label"])
return JSONResponse(content={"status": "success", "result": {"scores": scores, "labels": labels}}, status_code=200)
except Exception as e:
raise HTTPException(status_code=500, detail={"status": "error", "message": str(e)})
# =================================================================================================
# OBJECT DETECTION - detr_resnet_50
# =================================================================================================
@app.post("/object_detection/detr_resnet_50")
async def object_detection_detr_resnet_50(file: UploadFile = File(...)):
try:
data = await file.read()
image_bytes = core.object_detection(data, object_detection_detr_resnet_50_api_token)
# Parse the JSON string into a Python list of dictionaries
data_list = json.loads(image_bytes)
print(data_list)
scores = []
labels = []
segmented_pictures = []
for obj in data_list:
score = obj['score']
label = obj['label']
mask_base64 = obj['box']
# DO APPEND STUFF :D
scores.append(score)
labels.append(label)
segmented_pictures.append(mask_base64)
return JSONResponse(content={"status": "success", "Segmented Image": {"labels": labels, "scores": scores,
"segmented_pictures": segmented_pictures}},
status_code=200)
except Exception as e:
raise HTTPException(status_code=500, detail={"status": "error", "message": str(e)})
# =================================================================================================
# IMAGE TO IMAGE - gemini_opendalle
# =================================================================================================
@app.post("/image_to_image/gemini_opendalle/V1")
async def image_to_image_gemini_opendalleV1(file1: UploadFile = File(...), file2: UploadFile = File(...)):
try:
img1 = await file1.read()
img2 = await file2.read()
data = {"prompt": "i want you to give me the descripition of how would be the output image if we merged these two pictures toghther,you are not including all details please include them all and describe this image for me including all details as an example (gender . . .) and then MERGE THEM !!",
"role": "you are a professional image describer that gives all details about the input image in 500 words always"}
imgs_data = [img1, img2]
# implement gemmini vision
prompt = core.gemini_img2txt(data, imgs_data)
# transform the prompt into an image using gemini
image_bytes = core.text2image(prompt, txt2img_OPENDALLE_api_token)
# base64 Transformation
base64_encoded_image = base64.b64encode(image_bytes).decode('utf-8')
return JSONResponse(content={"status": "success", "Image": base64_encoded_image}, status_code=200)
except Exception as e:
raise HTTPException(status_code=500, detail={"status": "error", "message": str(e)})
# =================================================================================================
# EMOJI TO IMG - OPENDALLE_gemni
# =================================================================================================
@app.post("/emoji_to_image/OPENDALLE_gemni")
async def emoji_to_image():
try:
form = 0
emoji = await form.parse_form('prompt')
prompt = core.text_generation(emoji + " in one word what does emoji represent ?",
"ultra-realistic,16k,smooth,focus,super resolution,high-quality")
image_bytes = core.text2image(emoji + prompt, txt2img_OPENDALLE_api_token)
base64_encoded_image = base64.b64encode(image_bytes).decode('utf-8')
return JSONResponse(content={"status": "success", "image": base64_encoded_image}, status_code=200)
except Exception as e:
raise HTTPException(status_code=500, detail={"status": "error", "message": str(e)})
# =================================================================================================
# IMG TO EMOJI - gemini
# =================================================================================================
@app.post('/image_to_emoji/gemini')
async def image_to_emoji(file: UploadFile = File(...)):
try:
image = await file.read()
data = {"prompt": "transform this image into emojis, you can include more than a single emoji",
"role": "you should only use emojis no words are allowed"}
result = core.gemini_img2txt(data, [image])
return JSONResponse(content={"status": "success", "text": result}, status_code=200)
except Exception as e:
raise HTTPException(status_code=500, detail={"status": "error", "message": str(e)})