File size: 1,455 Bytes
602f5d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import FastAPI, UploadFile, File, HTTPException
from fastapi.responses import JSONResponse
from gradio_client import Client, handle_file
import shutil
import os
import base64
import os

app = FastAPI()
HF_TOKEN = os.getenv("HF_TOKEN")
# Initialize the Gradio client with the token
client = Client("Makhinur/Bringingoldphotoliveagain", hf_token=HF_TOKEN)



@app.post("/upload/")
async def upload_image(file: UploadFile = File(...)):
    # Save the uploaded file to a temporary location
    temp_file_path = f"temp_{file.filename}"
    with open(temp_file_path, "wb") as buffer:
        shutil.copyfileobj(file.file, buffer)

    try:
        # Use Gradio client to process the image
        result = client.predict(
            img=handle_file(temp_file_path),
            api_name="/predict"
        )

        # Encode the processed image as base64
        with open(result[0], "rb") as image_file:
            encoded_image = base64.b64encode(image_file.read()).decode('utf-8')

        # Clean up the temporary file
        os.remove(temp_file_path)

        # Return the processed image as a base64 string
        return JSONResponse(content={"sketch_image_base64": f"data:image/png;base64,{encoded_image}"})

    except Exception as e:
        # Clean up the temporary file in case of an error
        if os.path.exists(temp_file_path):
            os.remove(temp_file_path)
        raise HTTPException(status_code=500, detail=str(e))