JasonFinley0821 commited on
Commit
319d52a
·
1 Parent(s): c594b47

feat : upgrade clearify

Browse files
Files changed (3) hide show
  1. app.py +47 -15
  2. app_DeblurGan_PyTorch.py +8 -1
  3. static/dont_delete.txt +0 -0
app.py CHANGED
@@ -1,5 +1,6 @@
1
- from fastapi import FastAPI, Request, Response, UploadFile, File
2
- from fastapi.responses import JSONResponse, StreamingResponse
 
3
 
4
  import traceback
5
  import torch
@@ -9,13 +10,17 @@ from PIL import Image
9
  import io
10
  import numpy as np
11
  import os
 
12
 
13
  from models.fpn_inception import FPNInception # 你自己的模型類別
14
 
 
 
15
  os.environ["TORCH_HOME"] = "./.cache"
16
  os.environ["HF_HOME"] = "./.cache"
17
  os.environ["TRANSFORMERS_CACHE"] = "./.cache"
18
  os.makedirs("./.cache", exist_ok=True)
 
19
 
20
  # =====================
21
  # 初始化模型
@@ -101,22 +106,49 @@ def greet_json(request: Request, response: Response):
101
  return JSONResponse(content={"message": "Hello World", "client": client_host})
102
 
103
  @app.post("/predict")
104
- async def predict(file: UploadFile = File(...)):
105
  try:
106
- # 讀取上傳圖片
107
- contents = await file.read()
108
- img = Image.open(io.BytesIO(contents)).convert("RGB")
109
-
110
- # 去模糊
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
  result = deblur_image_tiled(G, img, device)
112
 
113
- # 輸出為 bytes
114
- img_byte_arr = io.BytesIO()
115
- result.save(img_byte_arr, format="PNG")
116
- img_byte_arr.seek(0)
117
-
118
- # 直接回傳圖片
119
- return StreamingResponse(img_byte_arr, media_type="image/png")
 
 
 
 
 
 
 
 
 
 
 
120
 
121
  except Exception as e:
122
  import traceback
 
1
+ from fastapi import FastAPI, Request, Response
2
+ from fastapi.responses import JSONResponse
3
+ import requests
4
 
5
  import traceback
6
  import torch
 
10
  import io
11
  import numpy as np
12
  import os
13
+ from datetime import datetime
14
 
15
  from models.fpn_inception import FPNInception # 你自己的模型類別
16
 
17
+ STATIC_DIR = "static"
18
+
19
  os.environ["TORCH_HOME"] = "./.cache"
20
  os.environ["HF_HOME"] = "./.cache"
21
  os.environ["TRANSFORMERS_CACHE"] = "./.cache"
22
  os.makedirs("./.cache", exist_ok=True)
23
+ os.makedirs(STATIC_DIR, exist_ok=True)
24
 
25
  # =====================
26
  # 初始化模型
 
106
  return JSONResponse(content={"message": "Hello World", "client": client_host})
107
 
108
  @app.post("/predict")
109
+ async def predict( request: Request, response: Response ):
110
  try:
111
+ # 1️⃣ 讀取 form-data
112
+ form = await request.form()
113
+ file_name = form.get("file_name")
114
+ file_format = form.get("file_format")
115
+ file_url = form.get("file_url")
116
+ file_width = int(form.get("file_width", 0))
117
+ file_height = int(form.get("file_height", 0))
118
+ file_created_at = form.get("file_created_at")
119
+
120
+ if not file_url:
121
+ return JSONResponse(
122
+ {"status": "error", "message": "file_url is required"},
123
+ status_code=400
124
+ )
125
+
126
+ # 2️⃣ 從 URL 下載圖片
127
+ resp = requests.get(file_url)
128
+ resp.raise_for_status()
129
+ img = Image.open(io.BytesIO(resp.content)).convert("RGB")
130
+
131
+ # 3️⃣ 去模糊
132
  result = deblur_image_tiled(G, img, device)
133
 
134
+ # 4️⃣ 產生檔名
135
+ base_name = f"{file_name}_{file_width}_{file_height}_{file_created_at}.jpg"
136
+ file_path = os.path.join(STATIC_DIR, base_name)
137
+
138
+ # 5️⃣ 儲存到 static
139
+ result.save(file_path, format="jpg")
140
+
141
+ # 6️⃣ 回傳前端可取用的 URL
142
+ file_url_return = str(request.base_url) + f"static/{base_name}"
143
+ return {
144
+ "status": "success",
145
+ "file_url": file_url_return,
146
+ "file_name": base_name,
147
+ "file_format": "jpg",
148
+ "file_width": result.width,
149
+ "file_height": result.height,
150
+ "file_created_at": datetime.now().strftime("%Y%m%d%H%M%S")
151
+ }
152
 
153
  except Exception as e:
154
  import traceback
app_DeblurGan_PyTorch.py CHANGED
@@ -27,13 +27,15 @@ print(f"🔹 Using device: {device}")
27
 
28
  # 模型 checkpoint 路徑
29
  checkpoint_dir = os.path.join(os.getcwd(), "model")
30
- ckpt_path = os.path.join(checkpoint_dir, "deblurgan_v2_latest.pth")
31
 
32
  # 初始化模型
33
  G = FPNInception(norm_layer=nn.InstanceNorm2d).to(device)
34
  checkpoint = torch.load(ckpt_path, map_location=device)
35
  G.load_state_dict(checkpoint["G"], strict=False)
 
36
  G.eval()
 
37
  print("✅ Model loaded from", ckpt_path)
38
 
39
 
@@ -145,6 +147,11 @@ class ImageViewerApp:
145
  self.canvas_original.image = photo
146
 
147
  result_img = self.model.predict(image_path)
 
 
 
 
 
148
  result_img.thumbnail((480, 420))
149
  photo_result = ImageTk.PhotoImage(result_img)
150
  self.canvas_result.create_image(0, 0, anchor="nw", image=photo_result)
 
27
 
28
  # 模型 checkpoint 路徑
29
  checkpoint_dir = os.path.join(os.getcwd(), "model")
30
+ ckpt_path = os.path.join(checkpoint_dir, "deblurgan_v2_latest_L1_vgg_D_jason_r20.pth")
31
 
32
  # 初始化模型
33
  G = FPNInception(norm_layer=nn.InstanceNorm2d).to(device)
34
  checkpoint = torch.load(ckpt_path, map_location=device)
35
  G.load_state_dict(checkpoint["G"], strict=False)
36
+ num_epoch = checkpoint["epoch"] + 1
37
  G.eval()
38
+ print("✅ num epoch", num_epoch)
39
  print("✅ Model loaded from", ckpt_path)
40
 
41
 
 
147
  self.canvas_original.image = photo
148
 
149
  result_img = self.model.predict(image_path)
150
+
151
+ saveimg_dir = os.path.join(os.getcwd(), "rimg")
152
+ #saveimg_path = os.path.join(saveimg_dir, "result_fullsize.png")
153
+
154
+ #result_img.save(saveimg_path)
155
  result_img.thumbnail((480, 420))
156
  photo_result = ImageTk.PhotoImage(result_img)
157
  self.canvas_result.create_image(0, 0, anchor="nw", image=photo_result)
static/dont_delete.txt ADDED
File without changes