Create main.py
Browse files
main.py
ADDED
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, UploadFile, File, HTTPException
|
2 |
+
from fastapi.responses import JSONResponse
|
3 |
+
from gradio_client import Client, handle_file
|
4 |
+
import shutil
|
5 |
+
import os
|
6 |
+
import base64
|
7 |
+
import os
|
8 |
+
|
9 |
+
app = FastAPI()
|
10 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
11 |
+
# Initialize the Gradio client with the token
|
12 |
+
client = Client("Makhinur/Bringingoldphotoliveagain", hf_token=HF_TOKEN)
|
13 |
+
|
14 |
+
|
15 |
+
|
16 |
+
@app.post("/upload/")
|
17 |
+
async def upload_image(file: UploadFile = File(...)):
|
18 |
+
# Save the uploaded file to a temporary location
|
19 |
+
temp_file_path = f"temp_{file.filename}"
|
20 |
+
with open(temp_file_path, "wb") as buffer:
|
21 |
+
shutil.copyfileobj(file.file, buffer)
|
22 |
+
|
23 |
+
try:
|
24 |
+
# Use Gradio client to process the image
|
25 |
+
result = client.predict(
|
26 |
+
img=handle_file(temp_file_path),
|
27 |
+
api_name="/predict"
|
28 |
+
)
|
29 |
+
|
30 |
+
# Encode the processed image as base64
|
31 |
+
with open(result[0], "rb") as image_file:
|
32 |
+
encoded_image = base64.b64encode(image_file.read()).decode('utf-8')
|
33 |
+
|
34 |
+
# Clean up the temporary file
|
35 |
+
os.remove(temp_file_path)
|
36 |
+
|
37 |
+
# Return the processed image as a base64 string
|
38 |
+
return JSONResponse(content={"sketch_image_base64": f"data:image/png;base64,{encoded_image}"})
|
39 |
+
|
40 |
+
except Exception as e:
|
41 |
+
# Clean up the temporary file in case of an error
|
42 |
+
if os.path.exists(temp_file_path):
|
43 |
+
os.remove(temp_file_path)
|
44 |
+
raise HTTPException(status_code=500, detail=str(e))
|
45 |
+
|