Create main.py
Browse files
main.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, File, UploadFile, HTTPException
|
| 2 |
+
from fastapi.responses import FileResponse
|
| 3 |
+
from gradio_client import Client, handle_file
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
# Initialize FastAPI
|
| 8 |
+
app = FastAPI()
|
| 9 |
+
|
| 10 |
+
# Retrieve the Hugging Face token from the environment
|
| 11 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 12 |
+
|
| 13 |
+
# Initialize the Gradio client with the token
|
| 14 |
+
client = Client("Makhinur/Its", hf_token=HF_TOKEN)
|
| 15 |
+
|
| 16 |
+
@app.post("/process-image/")
|
| 17 |
+
async def process_image(file: UploadFile = File(...)):
|
| 18 |
+
try:
|
| 19 |
+
# Save the uploaded file to a temporary location
|
| 20 |
+
file_location = f"temp_{file.filename}"
|
| 21 |
+
with open(file_location, "wb") as f:
|
| 22 |
+
f.write(await file.read())
|
| 23 |
+
|
| 24 |
+
# Use the Gradio client to send the image to the Gradio app
|
| 25 |
+
result = client.predict(
|
| 26 |
+
img=handle_file(file_location),
|
| 27 |
+
api_name="/predict"
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
# Clean up the temporary file
|
| 31 |
+
os.remove(file_location)
|
| 32 |
+
|
| 33 |
+
# Return the result as a file response
|
| 34 |
+
sketch_image_path = result[0] # Path to the sketch image
|
| 35 |
+
result_file_path = result[1] # Path to the result file
|
| 36 |
+
|
| 37 |
+
# Here we assume you want to return the sketch image
|
| 38 |
+
return FileResponse(sketch_image_path, media_type="image/jpeg")
|
| 39 |
+
|
| 40 |
+
except Exception as e:
|
| 41 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 42 |
+
|