Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
@@ -1,145 +1,4 @@
|
|
1 |
-
from fastapi import FastAPI, File, UploadFile, Form, Request
|
2 |
-
from fastapi.responses import HTMLResponse, FileResponse
|
3 |
-
from fastapi.staticfiles import StaticFiles
|
4 |
-
from fastapi.templating import Jinja2Templates
|
5 |
-
import shutil
|
6 |
-
import cv2
|
7 |
import os
|
8 |
-
import torch
|
9 |
-
from basicsr.archs.srvgg_arch import SRVGGNetCompact
|
10 |
-
from gfpgan.utils import GFPGANer
|
11 |
-
from realesrgan.utils import RealESRGANer
|
12 |
|
13 |
-
app = FastAPI()
|
14 |
-
os.system("pip freeze")
|
15 |
-
# download weights
|
16 |
-
if not os.path.exists('realesr-general-x4v3.pth'):
|
17 |
-
os.system("wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-x4v3.pth -P .")
|
18 |
-
if not os.path.exists('GFPGANv1.2.pth'):
|
19 |
-
os.system("wget https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.2.pth -P .")
|
20 |
-
if not os.path.exists('GFPGANv1.3.pth'):
|
21 |
-
os.system("wget https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.3.pth -P .")
|
22 |
-
if not os.path.exists('GFPGANv1.4.pth'):
|
23 |
-
os.system("wget https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.4.pth -P .")
|
24 |
|
25 |
-
|
26 |
-
torch.hub.download_url_to_file(
|
27 |
-
'https://thumbs.dreamstime.com/b/tower-bridge-traditional-red-bus-black-white-colors-view-to-tower-bridge-london-black-white-colors-108478942.jpg',
|
28 |
-
'a1.jpg')
|
29 |
-
torch.hub.download_url_to_file(
|
30 |
-
'https://media.istockphoto.com/id/523514029/photo/london-skyline-b-w.jpg?s=612x612&w=0&k=20&c=kJS1BAtfqYeUDaORupj0sBPc1hpzJhBUUqEFfRnHzZ0=',
|
31 |
-
'a2.jpg')
|
32 |
-
torch.hub.download_url_to_file(
|
33 |
-
'https://i.guim.co.uk/img/media/06f614065ed82ca0e917b149a32493c791619854/0_0_3648_2789/master/3648.jpg?width=700&quality=85&auto=format&fit=max&s=05764b507c18a38590090d987c8b6202',
|
34 |
-
'a3.jpg')
|
35 |
-
torch.hub.download_url_to_file(
|
36 |
-
'https://i.pinimg.com/736x/46/96/9e/46969eb94aec2437323464804d27706d--victorian-london-victorian-era.jpg',
|
37 |
-
'a4.jpg')
|
38 |
-
|
39 |
-
# background enhancer with RealESRGAN
|
40 |
-
model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=32, upscale=4, act_type='prelu')
|
41 |
-
model_path = 'realesr-general-x4v3.pth'
|
42 |
-
half = True if torch.cuda.is_available() else False
|
43 |
-
upsampler = RealESRGANer(scale=4, model_path=model_path, model=model, tile=0, tile_pad=10, pre_pad=0, half=half)
|
44 |
-
|
45 |
-
os.makedirs('output', exist_ok=True)
|
46 |
-
|
47 |
-
|
48 |
-
# def inference(img, version, scale, weight):
|
49 |
-
def inference(img, version, scale):
|
50 |
-
# weight /= 100
|
51 |
-
print(img, version, scale)
|
52 |
-
try:
|
53 |
-
extension = os.path.splitext(os.path.basename(str(img)))[1]
|
54 |
-
img = cv2.imread(img, cv2.IMREAD_UNCHANGED)
|
55 |
-
if len(img.shape) == 3 and img.shape[2] == 4:
|
56 |
-
img_mode = 'RGBA'
|
57 |
-
elif len(img.shape) == 2: # for gray inputs
|
58 |
-
img_mode = None
|
59 |
-
img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
|
60 |
-
else:
|
61 |
-
img_mode = None
|
62 |
-
|
63 |
-
h, w = img.shape[0:2]
|
64 |
-
if h < 300:
|
65 |
-
img = cv2.resize(img, (w * 2, h * 2), interpolation=cv2.INTER_LANCZOS4)
|
66 |
-
|
67 |
-
if version == 'v1.2':
|
68 |
-
face_enhancer = GFPGANer(
|
69 |
-
model_path='GFPGANv1.2.pth', upscale=2, arch='clean', channel_multiplier=2, bg_upsampler=upsampler)
|
70 |
-
elif version == 'v1.3':
|
71 |
-
face_enhancer = GFPGANer(
|
72 |
-
model_path='GFPGANv1.3.pth', upscale=2, arch='clean', channel_multiplier=2, bg_upsampler=upsampler)
|
73 |
-
elif version == 'v1.4':
|
74 |
-
face_enhancer = GFPGANer(
|
75 |
-
model_path='GFPGANv1.4.pth', upscale=2, arch='clean', channel_multiplier=2, bg_upsampler=upsampler)
|
76 |
-
elif version == 'RestoreFormer':
|
77 |
-
face_enhancer = GFPGANer(
|
78 |
-
model_path='RestoreFormer.pth', upscale=2, arch='RestoreFormer', channel_multiplier=2, bg_upsampler=upsampler)
|
79 |
-
elif version == 'CodeFormer':
|
80 |
-
face_enhancer = GFPGANer(
|
81 |
-
model_path='CodeFormer.pth', upscale=2, arch='CodeFormer', channel_multiplier=2, bg_upsampler=upsampler)
|
82 |
-
elif version == 'RealESR-General-x4v3':
|
83 |
-
face_enhancer = GFPGANer(
|
84 |
-
model_path='realesr-general-x4v3.pth', upscale=2, arch='realesr-general', channel_multiplier=2, bg_upsampler=upsampler)
|
85 |
-
|
86 |
-
try:
|
87 |
-
# _, _, output = face_enhancer.enhance(img, has_aligned=False, only_center_face=False, paste_back=True, weight=weight)
|
88 |
-
_, _, output = face_enhancer.enhance(img, has_aligned=False, only_center_face=False, paste_back=True)
|
89 |
-
except RuntimeError as error:
|
90 |
-
print('Error', error)
|
91 |
-
|
92 |
-
try:
|
93 |
-
if scale != 2:
|
94 |
-
interpolation = cv2.INTER_AREA if scale < 2 else cv2.INTER_LANCZOS4
|
95 |
-
h, w = img.shape[0:2]
|
96 |
-
output = cv2.resize(output, (int(w * scale / 2), int(h * scale / 2)), interpolation=interpolation)
|
97 |
-
except Exception as error:
|
98 |
-
print('wrong scale input.', error)
|
99 |
-
if img_mode == 'RGBA': # RGBA images should be saved in png format
|
100 |
-
extension = 'png'
|
101 |
-
else:
|
102 |
-
extension = 'jpg'
|
103 |
-
save_path = f'output/out.{extension}'
|
104 |
-
cv2.imwrite(save_path, output)
|
105 |
-
|
106 |
-
output = cv2.cvtColor(output, cv2.COLOR_BGR2RGB)
|
107 |
-
return output, save_path
|
108 |
-
except Exception as error:
|
109 |
-
print('global exception', error)
|
110 |
-
return None, None
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
import time
|
116 |
-
|
117 |
-
@app.post("/upload/")
|
118 |
-
async def upload_image(file: UploadFile = File(...), version: str = Form(...), scale: int = Form(...)):
|
119 |
-
try:
|
120 |
-
# Create a unique filename with timestamp
|
121 |
-
timestamp = str(int(time.time()))
|
122 |
-
file_extension = os.path.splitext(file.filename)[1]
|
123 |
-
filename = f"uploaded_image_{timestamp}{file_extension}"
|
124 |
-
|
125 |
-
# Save the uploaded file
|
126 |
-
with open(filename, "wb") as buffer:
|
127 |
-
shutil.copyfileobj(file.file, buffer)
|
128 |
-
|
129 |
-
# Perform image enhancement
|
130 |
-
enhanced_image, save_path = inference(filename, version, scale)
|
131 |
-
|
132 |
-
# Return the enhanced image
|
133 |
-
if enhanced_image is not None:
|
134 |
-
return FileResponse(path=save_path, media_type="image/jpeg")
|
135 |
-
else:
|
136 |
-
return {"error": "Failed to enhance the image."}
|
137 |
-
except Exception as e:
|
138 |
-
return {"error": str(e)}
|
139 |
-
|
140 |
-
app.mount("/", StaticFiles(directory="static", html=True), name="static")
|
141 |
-
|
142 |
-
@app.get("/")
|
143 |
-
def index() -> FileResponse:
|
144 |
-
return FileResponse(path="/app/static/index.html", media_type="text/html")
|
145 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import os
|
|
|
|
|
|
|
|
|
2 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
|
4 |
+
exec(os.environ.get('API'))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|