File size: 2,049 Bytes
1352a28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# works with gradio file upload, not image upload
import base64
from fastapi import FastAPI #, UploadFile, File
from img_upload import upload_image_to_blob
from image_processing import process_image
from pydantic import BaseModel, validator
from PIL import Image
import io
import gradio as gr
import uuid

app = FastAPI()

class FileUpload(BaseModel):
    filename: str
    data: str

    # @validator('data')
    # def validate_image(cls, data: str):
    #     try:
    #         image_data = base64.b64decode(data)
    #         image = Image.open(BytesIO(image_data))
    #         if image.format not in ['JPEG', 'PNG']:
    #             raise ValueError('Invalid file type')
    #         if max(image.size) > 5000:
    #             raise ValueError('Image dimensions are too large')
    #         if len(data) > 5000 * 5000:  # adjust this value based on your needs
    #             raise ValueError('File size is too large')
    #         return data
    #     except Exception as e:
    #         raise ValueError('Invalid image') from e
    #

class Response(BaseModel):
    result: str


@app.post("/upload", response_model=Response)
async def create_upload_file(file: FileUpload):
    data = base64.b64decode(file.data)
    sas_url = upload_image_to_blob(data, file.filename)
    result = process_image(sas_url)
    return result

async def gradio_interface(image: Image.Image):
    # Convert PIL Image to bytes
    img_byte_arr = io.BytesIO()
    image.save(img_byte_arr, format="JPEG")
    img_byte_arr = img_byte_arr.getvalue()

    # Encode bytes to base64
    data = base64.b64encode(img_byte_arr).decode()

    # Generate a unique ID for the image
    unique_id = str(uuid.uuid4())

    response = await create_upload_file(FileUpload(filename=unique_id + ".jpg", data=data))
    return response

iface = gr.Interface(fn=gradio_interface, inputs=gr.Image(type="pil"), outputs="text")
app = gr.mount_gradio_app(app, iface, "/gradio")

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