Makhinur commited on
Commit
e482b3f
·
verified ·
1 Parent(s): ee3e372

Update main.py

Browse files

from fastapi import FastAPI, File, UploadFile, Form
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from gradio_client import Client, handle_file
import os
import tempfile
import base64

app = FastAPI()

# Setup CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Adjust as needed
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)

# Initialize Gradio client
hf_token = os.environ.get('HF_TOKEN')
client = Client("https://Makhinur/Image_Face_Upscale_Restoration-GFPGAN.hf.space/", hf_token=hf_token)



@app
.post("/upload/")
async def upload_file(file: UploadFile = File(...), version: str = Form(...), scale: int = Form(...)):
# Save the uploaded file temporarily
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
temp_file.write(await file.read())
temp_file_path = temp_file.name

try:
# Use handle_file to prepare the file for the Gradio client
result = client.predict(handle_file(temp_file_path), version, scale, api_name="/predict")

# Check if the result is valid
if result and len(result) == 2:
# Convert the image data to a base64 string
with open(result[0], "rb") as image_file:
image_data = base64.b64encode(image_file.read()).decode("utf-8")

return JSONResponse({
"sketch_image_base64": f"data:image/png;base64,{image_data}",
"result_file": result[1]
})
else:
return JSONResponse({"error": "Invalid result from the prediction API."}, status_code=500)
except Exception as e:
return JSONResponse({"error": str(e)}, status_code=500)
finally:
# Clean up the temporary file
if os.path.exists(temp_file_path):
os.unlink(temp_file_path)

Files changed (1) hide show
  1. main.py +3 -3
main.py CHANGED
@@ -1,7 +1,7 @@
1
  from fastapi import FastAPI, File, UploadFile, Form
2
  from fastapi.responses import JSONResponse
3
  from fastapi.middleware.cors import CORSMiddleware
4
- from gradio_client import Client
5
  import os
6
  import tempfile
7
  import base64
@@ -29,8 +29,8 @@ async def upload_file(file: UploadFile = File(...), version: str = Form(...), sc
29
  temp_file_path = temp_file.name
30
 
31
  try:
32
- # Call the Gradio API
33
- result = client.predict(temp_file_path, version, scale, api_name="/predict")
34
 
35
  # Check if the result is valid
36
  if result and len(result) == 2:
 
1
  from fastapi import FastAPI, File, UploadFile, Form
2
  from fastapi.responses import JSONResponse
3
  from fastapi.middleware.cors import CORSMiddleware
4
+ from gradio_client import Client, handle_file
5
  import os
6
  import tempfile
7
  import base64
 
29
  temp_file_path = temp_file.name
30
 
31
  try:
32
+ # Use handle_file to prepare the file for the Gradio client
33
+ result = client.predict(handle_file(temp_file_path), version, scale, api_name="/predict")
34
 
35
  # Check if the result is valid
36
  if result and len(result) == 2: