File size: 6,416 Bytes
b1f46e5
5d29343
b1f46e5
 
 
 
 
 
 
4722fbd
29dc177
473fa66
4b22123
a82c1e0
 
 
 
4b22123
ceb119d
b1f46e5
 
 
a82c1e0
 
 
 
 
 
 
 
485d5a3
a82c1e0
 
e194a66
a82c1e0
 
 
e194a66
485d5a3
 
 
 
 
 
 
 
 
a82c1e0
 
b1f46e5
 
ceb119d
1976616
b1f46e5
26e9f88
 
a82c1e0
f5ec736
 
a82c1e0
26e9f88
4722fbd
 
2c25e9c
9669421
b012c7d
 
c526434
 
4b98217
c526434
 
473fa66
c526434
 
473fa66
 
4722fbd
473fa66
b68e332
 
 
 
51a8240
b68e332
 
 
 
1976616
 
4722fbd
4b22123
 
 
1976616
3fca0b4
4b22123
 
3fca0b4
4b22123
 
 
 
1976616
b68e332
 
4b22123
3fca0b4
1976616
7928acb
8791de8
1373e60
b012c7d
7928acb
8791de8
7928acb
9beab52
8791de8
 
 
 
 
 
 
 
 
 
9beab52
 
 
 
8791de8
7928acb
 
 
 
 
 
 
 
4722fbd
9beab52
 
5d29343
9beab52
 
 
7ebdcd1
 
 
9beab52
 
 
 
 
 
 
 
 
 
 
 
7ebdcd1
9beab52
 
 
7ebdcd1
5d29343
7c14c4a
9beab52
 
5d29343
9beab52
4722fbd
 
a82c1e0
 
 
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
from fastapi import FastAPI ,Request ,Form, UploadFile, File
from fastapi.responses import HTMLResponse, FileResponse,StreamingResponse,JSONResponse
import os
import io
from PIL import ImageOps,Image ,ImageFilter
#from transformers import pipeline
import matplotlib.pyplot as plt
import numpy as np
import ast
from server import *
import cv2
from typing import Optional
import base64
from fastapi import FastAPI, Request
from slowapi import Limiter
from slowapi.util import get_remote_address
from fastapi.responses import JSONResponse


#http://localhost:8000
app = FastAPI()

limiter = Limiter(key_func=get_remote_address)
app.state.limiter = limiter
# Register the Limiter with FastAPI
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    response = await call_next(request)
    return response


@app.exception_handler(429)
async def rate_limit_exceeded(request: Request, exc):
    
    return JSONResponse(
        status_code=429,
        content={"detail": "Too Many Requests ,please just try 3 times per hour"},
    )
    '''
    return JSONResponse(
          status_code=429,
           content={
                "detail": "Too Many Requests ,please just try 3 times per hour",
                "status": 0
            })
    '''



# Root route
@app.get('/')
def main():
    return "Hello From Background remover !"

'''
#test limit
@app.post("/items")
@limiter.limit("3/hour")  # must have parameter request
async def read_items(request: Request, type_of_filters: str = Form(...)):
    return {"items": str(type_of_filters)}
'''

@app.post('/imageStep1')
async def image_step1(request: Request,image_file: UploadFile = File(...),background_image: Optional [UploadFile] = File(None),type_of_filters: str = Form(...), blur_radius: str = Form(...)):
        #return {"type ":type_of_filters ,"radius":blur_radius,"image":image_file,"back":background_image}
        #type_of_filters : cam / ...remove / ...back
        input_to_type_of_filters = None

        if background_image and background_image.filename:
                contents__back = await background_image.read()
                image_back = Image.open(io.BytesIO(contents__back))
                input_to_type_of_filters = image_back
        else:
               input_to_type_of_filters = type_of_filters

        contents_img = await image_file.read()
        image = Image.open(io.BytesIO(contents_img))
        

        output_step1 =SegmenterBackground().Back_step1(image,input_to_type_of_filters,int(blur_radius))

        if (output_step1[-1] == 0):
            return {
                "detail": output_step1[0],
                "status": output_step1[-1]
            }
        
        produced_image = output_step1[0]
        
        '''
        # Save the processed image to a temporary file
        #output_file_path_tmp = "/tmp/tmp_processed_image.png"
        #produced_image.save(output_file_path_tmp)
        # return FileResponse(output_file_path_tmp, media_type='image/png', filename="/tmp/tmp_processed_image.png")
        '''
        
        # Convert the image to base64 to return it in the response
        buffered = io.BytesIO()
        produced_image.save(buffered, format="PNG")
        encoded_img = base64.b64encode(buffered.getvalue()).decode("utf-8")
            
        # Returning both text and the base64 image
        return {
                "message": output_step1[1],
                "image_base64": encoded_img,
                "status": output_step1[-1]
        }
        

@app.post('/imageStep2')
async def image_step2(image_file: UploadFile = File(...),background_image: Optional [UploadFile] = File(None),type_of_filters: str = Form(...),
                      things_replace: str = Form(...), blur_radius: str = Form(...)):
            #things_replace : from what detected.
        things_replace=ast.literal_eval(things_replace)
        blur_radius=int(blur_radius)


        input_to_type_of_filters=None

        if background_image and background_image.filename:
                contents__back = await background_image.read()
                image_back = Image.open(io.BytesIO(contents__back))
                input_to_type_of_filters = image_back
        else:
               input_to_type_of_filters = type_of_filters


        contents = await image_file.read()
        image = Image.open(io.BytesIO(contents))
        

        produced_image=SegmenterBackground().Back_step2(image,input_to_type_of_filters,things_replace,int(blur_radius))

        # Save the processed image to a temporary file
        output_file_path_tmp = "/tmp/tmp_processed_image.png"
        produced_image.save(output_file_path_tmp)

        # Return the processed image for download
        return FileResponse(output_file_path_tmp, media_type='image/png', filename="/tmp/tmp_processed_image.png")
    



@app.post('/Video')
async def Video(video_file: UploadFile = File(...),background_image: Optional [UploadFile] = File(None),kind_back: str = Form(...) 
                ,type_of_filters: str = Form(...),blur_radius: str = Form(...)):#--->,background_image: UploadFile = File(...)):
        
        #video_data = await video_file.read()
        #nparr = np.frombuffer(video_data, np.uint8)
        #video_path=cv2.imdecode(nparr, cv2.IMREAD_COLOR) #named this as just passed as it's path
        blur_radius=int(blur_radius)
        kind_back=ast.literal_eval(kind_back)

        input_to_type_of_filters=None

        if background_image and background_image.filename:
                contents__back = await background_image.read()
                image_back = Image.open(io.BytesIO(contents__back))
                input_to_type_of_filters = image_back
        else:
               input_to_type_of_filters = type_of_filters


        input_path_toWrite = f'/tmp/tmp_imput.avi'#{video_file.filename}
        output_path = '/tmp/tmp_output.avi'
        with open(input_path_toWrite, 'wb') as f:
            f.write(await video_file.read())

        #--------> mp4? (when tried ,worked on it although)   sound??

        SegmenterBackground().Back_video(input_path_toWrite, output_path,input_to_type_of_filters,kind_back,blur_radius)#video,background_image,what_remove,blur_radius=23)
        
        return StreamingResponse(open(output_path, "rb"), media_type="video/avi")


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)