Spaces:
Runtime error
Runtime error
Update main.py
Browse files
main.py
CHANGED
@@ -1,142 +1,25 @@
|
|
1 |
-
from fastapi import FastAPI,
|
2 |
-
from fastapi
|
3 |
from fastapi.responses import HTMLResponse, FileResponse
|
4 |
from fastapi.staticfiles import StaticFiles
|
5 |
-
from
|
6 |
-
import
|
7 |
-
import
|
8 |
-
from fastai.vision import *
|
9 |
-
from fastai.utils.mem import *
|
10 |
-
from fastai.vision import open_image, load_learner, image, torch
|
11 |
-
import numpy as np
|
12 |
-
import urllib.request
|
13 |
-
import PIL.Image
|
14 |
-
from io import BytesIO
|
15 |
-
import torchvision.transforms as T
|
16 |
-
from PIL import Image
|
17 |
-
import requests
|
18 |
-
from io import BytesIO
|
19 |
-
import fastai
|
20 |
-
from fastai.vision import *
|
21 |
-
from fastai.utils.mem import *
|
22 |
-
from fastai.vision import open_image, load_learner, image, torch
|
23 |
-
import numpy as np
|
24 |
-
import urllib.request
|
25 |
-
import PIL.Image
|
26 |
-
from PIL import Image
|
27 |
-
from io import BytesIO
|
28 |
-
import torchvision.transforms as T
|
29 |
-
import requests
|
30 |
-
import model_loader
|
31 |
|
32 |
app = FastAPI()
|
33 |
|
34 |
-
|
35 |
-
|
36 |
-
MODEL_FILENAME = "ArtLine_920.pkl"
|
37 |
-
if not os.path.exists(MODEL_FILENAME):
|
38 |
-
model_loader.download_model(MODEL_URL, MODEL_FILENAME)
|
39 |
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
super().__init__()
|
47 |
-
self.m_feat = m_feat
|
48 |
-
self.loss_features = [self.m_feat[i] for i in layer_ids]
|
49 |
-
self.hooks = hook_outputs(self.loss_features, detach=False)
|
50 |
-
self.wgts = layer_wgts
|
51 |
-
self.metric_names = ['pixel',] + [f'feat_{i}' for i in range(len(layer_ids))
|
52 |
-
] + [f'gram_{i}' for i in range(len(layer_ids))]
|
53 |
-
|
54 |
-
def make_features(self, x, clone=False):
|
55 |
-
self.m_feat(x)
|
56 |
-
return [(o.clone() if clone else o) for o in self.hooks.stored]
|
57 |
-
|
58 |
-
def forward(self, input, target):
|
59 |
-
out_feat = self.make_features(target, clone=True)
|
60 |
-
in_feat = self.make_features(input)
|
61 |
-
self.feat_losses = [base_loss(input,target)]
|
62 |
-
self.feat_losses += [base_loss(f_in, f_out)*w
|
63 |
-
for f_in, f_out, w in zip(in_feat, out_feat, self.wgts)]
|
64 |
-
self.feat_losses += [base_loss(gram_matrix(f_in), gram_matrix(f_out))*w**2 * 5e3
|
65 |
-
for f_in, f_out, w in zip(in_feat, out_feat, self.wgts)]
|
66 |
-
self.metrics = dict(zip(self.metric_names, self.feat_losses))
|
67 |
-
return sum(self.feat_losses)
|
68 |
-
|
69 |
-
def __del__(self): self.hooks.remove()
|
70 |
-
|
71 |
-
def add_margin(pil_img, top, right, bottom, left, color):
|
72 |
-
width, height = pil_img.size
|
73 |
-
new_width = width + right + left
|
74 |
-
new_height = height + top + bottom
|
75 |
-
result = Image.new(pil_img.mode, (new_width, new_height), color)
|
76 |
-
result.paste(pil_img, (left, top))
|
77 |
-
return result
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
import gradio as gr
|
84 |
-
import cv2
|
85 |
-
|
86 |
-
|
87 |
-
def get_filename(prefix="sketch"):
|
88 |
-
from datetime import datetime
|
89 |
-
from pytz import timezone
|
90 |
-
return datetime.now(timezone('Asia/Seoul')).strftime('sketch__%Y-%m-%d %H:%M:%S.jpg')
|
91 |
-
|
92 |
-
def predict(img):
|
93 |
-
img = PIL.Image.fromarray(img)
|
94 |
-
img = add_margin(img, 250, 250, 250, 250, (255, 255, 255))
|
95 |
-
img = np.array(img)
|
96 |
-
|
97 |
-
h, w = img.shape[:-1]
|
98 |
-
cv2.imwrite("test.jpg", img)
|
99 |
-
img_test = open_image("test.jpg")
|
100 |
-
|
101 |
-
p,img_hr,b = learn.predict(img_test)
|
102 |
-
|
103 |
-
res = (img_hr / img_hr.max()).numpy()
|
104 |
-
res = res[0] # take only first channel as result
|
105 |
-
res = cv2.resize(res, (w,h))
|
106 |
-
|
107 |
-
output_file = get_filename()
|
108 |
-
|
109 |
-
cv2.imwrite(output_file, (res * 255).astype(np.uint8), [cv2.IMWRITE_JPEG_QUALITY, 50])
|
110 |
-
|
111 |
-
return res, output_file
|
112 |
-
|
113 |
-
@app.post("/predict/")
|
114 |
-
async def predict(file: UploadFile = File(...)) -> Tuple[str, bytes]:
|
115 |
-
contents = await file.read()
|
116 |
-
img = cv2.imdecode(np.fromstring(contents, np.uint8), cv2.IMREAD_COLOR)
|
117 |
-
img = PIL.Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
|
118 |
-
img = add_margin(img, 250, 250, 250, 250, (255, 255, 255))
|
119 |
-
img = np.array(img)
|
120 |
-
|
121 |
-
h, w = img.shape[:-1]
|
122 |
-
cv2.imwrite("test.jpg", img)
|
123 |
-
img_test = open_image("test.jpg")
|
124 |
-
|
125 |
-
p,img_hr,b = learn.predict(img_test)
|
126 |
-
|
127 |
-
res = (img_hr / img_hr.max()).numpy()
|
128 |
-
res = res[0] # take only first channel as result
|
129 |
-
res = cv2.resize(res, (w,h))
|
130 |
-
|
131 |
-
output_file = get_filename()
|
132 |
-
|
133 |
-
cv2.imwrite(output_file, (res * 255).astype(np.uint8), [cv2.IMWRITE_JPEG_QUALITY, 50])
|
134 |
-
|
135 |
-
return output_file, res.tobytes()
|
136 |
|
137 |
app.mount("/", StaticFiles(directory="static", html=True), name="static")
|
138 |
|
139 |
@app.get("/")
|
140 |
def index() -> FileResponse:
|
141 |
-
return FileResponse(path="/app/static/index.html", media_type="text/html")
|
142 |
-
|
|
|
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 gradio_client import Client
|
7 |
+
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
|
9 |
app = FastAPI()
|
10 |
|
11 |
+
hf_token = os.environ.get('HF_TOKEN')
|
12 |
+
client = Client("https://ashrafb-image-to-sketch.hf.space/", hf_token=hf_token)
|
|
|
|
|
|
|
13 |
|
14 |
+
@app.post("/predict")
|
15 |
+
async def predict_sketch(file: UploadFile = File(...)):
|
16 |
+
content = await file.read()
|
17 |
+
# Call the Gradio client to get the sketch result
|
18 |
+
result = client.predict(content, api_name="/predict")
|
19 |
+
return {"sketch_image": result[0], "result_file": result[1]}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
20 |
|
21 |
app.mount("/", StaticFiles(directory="static", html=True), name="static")
|
22 |
|
23 |
@app.get("/")
|
24 |
def index() -> FileResponse:
|
25 |
+
return FileResponse(path="/app/static/index.html", media_type="text/html")
|
|