Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
@@ -1,4 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import os
|
|
|
|
|
2 |
|
|
|
|
|
3 |
|
4 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, File, UploadFile
|
2 |
+
from fastapi import FastAPI, File, UploadFile, Form, Request
|
3 |
+
from fastapi.responses import HTMLResponse, FileResponse
|
4 |
+
from fastapi.staticfiles import StaticFiles
|
5 |
+
from fastapi.templating import Jinja2Templates
|
6 |
+
from fastapi import FastAPI, File, UploadFile, HTTPException
|
7 |
+
from fastapi.responses import JSONResponse
|
8 |
+
from fastapi.responses import StreamingResponse
|
9 |
+
from gradio_client import Client
|
10 |
import os
|
11 |
+
import io
|
12 |
+
app = FastAPI()
|
13 |
|
14 |
+
hf_token = os.environ.get('HF_TOKEN')
|
15 |
+
client = Client("https://ashrafb-image-face-upscale-restoration-gfpgan.hf.space/", hf_token=hf_token)
|
16 |
|
17 |
+
import tempfile
|
18 |
+
|
19 |
+
|
20 |
+
|
21 |
+
import base64
|
22 |
+
|
23 |
+
@app.post("/upload/")
|
24 |
+
async def upload_file(file: UploadFile = File(...), version: str = Form(...), scale: int = Form(...)):
|
25 |
+
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
|
26 |
+
temp_file.write(await file.read())
|
27 |
+
temp_file_path = temp_file.name
|
28 |
+
|
29 |
+
try:
|
30 |
+
result = client.predict(temp_file_path, api_name="/predict")
|
31 |
+
|
32 |
+
# Check if the result is valid
|
33 |
+
if result and len(result) == 2:
|
34 |
+
# Convert the image data to base64 string
|
35 |
+
with open(result[0], "rb") as image_file:
|
36 |
+
image_data = base64.b64encode(image_file.read()).decode("utf-8")
|
37 |
+
|
38 |
+
return {
|
39 |
+
"sketch_image_base64": f"data:image/png;base64,{image_data}",
|
40 |
+
"result_file": result[1]
|
41 |
+
}
|
42 |
+
else:
|
43 |
+
return {"error": "Invalid result from the prediction API."}
|
44 |
+
except Exception as e:
|
45 |
+
return {"error": str(e)}
|
46 |
+
finally:
|
47 |
+
if os.path.exists(temp_file_path):
|
48 |
+
os.unlink(temp_file_path)
|
49 |
+
|
50 |
+
|
51 |
+
app.mount("/", StaticFiles(directory="static", html=True), name="static")
|
52 |
+
|
53 |
+
@app.get("/")
|
54 |
+
def index() -> FileResponse:
|
55 |
+
return FileResponse(path="/app/static/index.html", media_type="text/html")
|