ning8429 commited on
Commit
c507cd4
·
verified ·
1 Parent(s): 75856bb

Update api_server.py

Browse files
Files changed (1) hide show
  1. api_server.py +31 -22
api_server.py CHANGED
@@ -6,6 +6,7 @@ import torchvision.transforms as transforms
6
  from pathlib import Path
7
  from ultralytics import YOLO
8
  import io
 
9
 
10
  # Disable tensorflow warnings
11
  os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
@@ -47,6 +48,13 @@ elif load_type == 'remote_hub_from_pretrained':
47
  else:
48
  raise AssertionError('No load type is specified!')
49
 
 
 
 
 
 
 
 
50
  # Initialize the Flask application
51
  app = Flask(__name__)
52
 
@@ -54,6 +62,9 @@ app = Flask(__name__)
54
  # API route for prediction(YOLO)
55
  @app.route('/predict', methods=['POST'])
56
  def predict():
 
 
 
57
  if 'image' not in request.files:
58
  # Handle if no file is selected
59
  return 'No file selected'
@@ -93,28 +104,26 @@ def predict():
93
 
94
  # 儲存辨識後的圖片到指定資料夾
95
  for result in results:
96
- # 保存完整圖片
97
- yolo_path = f'{YOLO_DIR}/results_{Path(result.path).name}'
98
- result.save(yolo_path)
99
- saved_images.append(yolo_path)
100
-
101
- # 保存裁剪後的圖片(僅當 save_crop 返回有效的路徑時才加入)
102
- cropped_images = result.save_crop(YOLO_DIR) # 有些 YOLO 版本 save_crop 不返回值
103
- if cropped_images: # 確保不會對 None 進行迭代
104
- if isinstance(cropped_images, list): # 如果它返回一個列表
105
- saved_images.extend(cropped_images)
106
- else:
107
- saved_images.append(cropped_images)
108
-
109
- end_time = time.time()
110
- inference_time = end_time - start_time
111
-
112
- # 返回辨識結果的文件路徑以及推理時間
113
- return jsonify({
114
- 'saved_images': saved_images,
115
- 'inference_time': inference_time
116
- }), 200
117
-
118
 
119
 
120
  # # dictionary is not a JSON: https://www.quora.com/What-is-the-difference-between-JSON-and-a-dictionary
 
6
  from pathlib import Path
7
  from ultralytics import YOLO
8
  import io
9
+ import base64
10
 
11
  # Disable tensorflow warnings
12
  os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
 
48
  else:
49
  raise AssertionError('No load type is specified!')
50
 
51
+
52
+ def image_to_base64(image_path):
53
+ with open(image_path, "rb") as image_file:
54
+ encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
55
+ return encoded_string
56
+
57
+
58
  # Initialize the Flask application
59
  app = Flask(__name__)
60
 
 
62
  # API route for prediction(YOLO)
63
  @app.route('/predict', methods=['POST'])
64
  def predict():
65
+
66
+ user_id = request.args.get('user_id')
67
+
68
  if 'image' not in request.files:
69
  # Handle if no file is selected
70
  return 'No file selected'
 
104
 
105
  # 儲存辨識後的圖片到指定資料夾
106
  for result in results:
107
+ # 保存圖片
108
+ result.save_crop(f"{YOLO_DIR}/{user_id}")
109
+
110
+ num_detections = len(result.boxes) # Get the number of detections
111
+ labels = result.boxes.cls # Get predicted label IDs
112
+ label_names = [model.names[int(label)] for label in labels] # Convert to names
113
+
114
+ encoded_images=[]
115
+
116
+ for label_name in label_names:
117
+ output_file=f"{YOLO_DIR}/{user_id}/{label_name}/im.jpg.jpg"
118
+ # 將圖片轉換為 base64 編碼
119
+ encoded_images.append(image_to_base64(output_file))
120
+
121
+ # 建立回應資料
122
+ response_data = {
123
+ 'images': encoded_images,
124
+ 'description': label_names
125
+ }
126
+ return jsonify(response_data)
 
 
127
 
128
 
129
  # # dictionary is not a JSON: https://www.quora.com/What-is-the-difference-between-JSON-and-a-dictionary