Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

api.py 7.8 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
  1. # from fastapi import FastAPI, File, UploadFile, Form, HTTPException
  2. # from pydantic import BaseModel
  3. # from typing import Optional
  4. # import uuid
  5. # import io
  6. # import cv2
  7. # import numpy as np
  8. # from helper import load_model, show_model_not_loaded_warning, model_path
  9. # import logging
  10. # import os
  11. # logger = logging.getLogger(__name__)
  12. # app = FastAPI()
  13. # class_names = {0: "Fitoftora", 1: "Monilia", 2: "Sana", 3: "Healthy"}
  14. # class PredictionInfo(BaseModel):
  15. # nb_classe: int
  16. # nb_box: int
  17. # confidence_min: float
  18. # pred_classes: set
  19. # bbx_coordinates: list[tuple[float, float, float, float, float]]
  20. # pred_img_id: uuid.UUID
  21. # box_id: uuid.UUID
  22. # diseases_id: uuid.UUID
  23. # det_image_path: str
  24. # def predict_image(confidence: float, image_bytes: bytes, model):
  25. # try:
  26. # nparr = np.frombuffer(image_bytes, np.uint8)
  27. # image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
  28. # if image is None:
  29. # raise HTTPException(
  30. # status_code=400,
  31. # detail="L'image est vide. Assurez-vous de télécharger une image valide."
  32. # )
  33. # # Convert image to RGB
  34. # image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
  35. # res = model.predict(image_rgb, conf=confidence)
  36. # nb_classe = len(set(res[0].boxes.cls.tolist()))
  37. # nb_box = len(res[0].boxes)
  38. # confidence_min = min(res[0].boxes.conf.tolist())
  39. # pred_classes = set([class_names[int(box.cls.item())] for box in res[0].boxes])
  40. # pred_img_id = uuid.uuid4()
  41. # box_id = uuid.uuid4()
  42. # diseases_id = uuid.uuid4()
  43. # # Normalisation des coordonnées des boîtes englobantes
  44. # bbx_coordinates = [
  45. # (box.xyxy[0][0], box.xyxy[0][1],
  46. # box.xyxy[0][2], box.xyxy[0][3], box.conf)
  47. # for box in res[0].boxes]
  48. # # Define image saving path for debugging (optional)
  49. # current_directory = os.getcwd()
  50. # IMAGE_SAVE_PATH = os.path.join(current_directory, "images_bbx")
  51. # os.makedirs(IMAGE_SAVE_PATH, exist_ok=True)
  52. # image_with_boxes_path = os.path.join(IMAGE_SAVE_PATH, f"imagebbx_{pred_img_id}.jpg")
  53. # res_plotted = res[0].plot()[:, :, ::-1]
  54. # cv2.imwrite(image_with_boxes_path, res_plotted)
  55. # return PredictionInfo(
  56. # pred_img_id=pred_img_id,
  57. # diseases_id=diseases_id,
  58. # box_id=box_id,
  59. # nb_classe=nb_classe,
  60. # nb_box=nb_box,
  61. # confidence_min=confidence_min,
  62. # pred_classes=pred_classes,
  63. # bbx_coordinates=bbx_coordinates,
  64. # det_image_path=image_with_boxes_path
  65. # )
  66. # except Exception as e:
  67. # logger.exception("Une erreur est survenue pendant la prédiction : %s", e)
  68. # raise HTTPException(status_code=500, detail="Une erreur interne est survenue.")
  69. # @app.post("/predict_image/")
  70. # async def predict_image_route(confidence: float = Form(...), image: UploadFile = File(...)):
  71. # try:
  72. # model = load_model(model_path)
  73. # image_bytes = await image.read()
  74. # return predict_image(confidence, image_bytes, model)
  75. # except HTTPException as e:
  76. # raise e
  77. # except Exception as e:
  78. # logger.exception("Une erreur interne est survenue lors de la prédiction d'image.")
  79. # raise HTTPException(status_code=500, detail="Une erreur interne est survenue.")
  80. from fastapi import FastAPI, File, UploadFile, Form, HTTPException
  81. from pydantic import BaseModel
  82. from typing import Optional
  83. import uuid
  84. import io
  85. import cv2
  86. import numpy as np
  87. from helper import load_model, show_model_not_loaded_warning, model_path
  88. import logging
  89. import os
  90. import urllib.parse
  91. from starlette.responses import FileResponse
  92. logger = logging.getLogger(__name__)
  93. app = FastAPI()
  94. class_names = {0: "Fitoftora", 1: "Monilia", 2: "Sana", 3: "Healthy"}
  95. class PredictionInfo(BaseModel):
  96. nb_classe: int
  97. nb_box: int
  98. confidence_min: float
  99. pred_classes: set
  100. bbx_coordinates: list[tuple[float, float, float, float, float]]
  101. pred_img_id: uuid.UUID
  102. box_id: uuid.UUID
  103. diseases_id: uuid.UUID
  104. det_image_path: str
  105. def predict_image(confidence: float, image_bytes: bytes, model):
  106. try:
  107. nparr = np.frombuffer(image_bytes, np.uint8)
  108. image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
  109. if image is None:
  110. raise HTTPException(
  111. status_code=400,
  112. detail="L'image est vide. Assurez-vous de télécharger une image valide."
  113. )
  114. # Convertir l'image en RGB
  115. image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
  116. res = model.predict(image_rgb, conf=confidence)
  117. nb_classe = len(set(res[0].boxes.cls.tolist()))
  118. nb_box = len(res[0].boxes)
  119. confidence_min = min(res[0].boxes.conf.tolist())
  120. pred_classes = set([class_names[int(box.cls.item())] for box in res[0].boxes])
  121. pred_img_id = uuid.uuid4()
  122. box_id = uuid.uuid4()
  123. diseases_id = uuid.uuid4()
  124. # Normaliser les coordonnées des boîtes englobantes
  125. bbx_coordinates = [
  126. (box.xyxy[0][0], box.xyxy[0][1],
  127. box.xyxy[0][2], box.xyxy[0][3], box.conf)
  128. for box in res[0].boxes]
  129. # Définir le chemin d'enregistrement de l'image pour le débogage (optionnel)
  130. current_directory = os.getcwd()
  131. IMAGE_SAVE_PATH = os.path.join(current_directory, "images_bbx")
  132. os.makedirs(IMAGE_SAVE_PATH, exist_ok=True)
  133. image_with_boxes_path = os.path.join(IMAGE_SAVE_PATH, f"imagebbx_{pred_img_id}.jpg")
  134. res_plotted = res[0].plot()[:, :, ::-1]
  135. cv2.imwrite(image_with_boxes_path, res_plotted)
  136. return PredictionInfo(
  137. pred_img_id=pred_img_id,
  138. diseases_id=diseases_id,
  139. box_id=box_id,
  140. nb_classe=nb_classe,
  141. nb_box=nb_box,
  142. confidence_min=confidence_min,
  143. pred_classes=pred_classes,
  144. bbx_coordinates=bbx_coordinates,
  145. det_image_path=image_with_boxes_path
  146. )
  147. except Exception as e:
  148. logger.exception("Une erreur est survenue pendant la prédiction : %s", e)
  149. raise HTTPException(status_code=500, detail="Une erreur interne est survenue.")
  150. @app.post("/predict_image/")
  151. async def predict_image_route(confidence: float = Form(...), image: UploadFile = File(...)):
  152. try:
  153. model = load_model(model_path)
  154. image_bytes = await image.read()
  155. prediction_info = predict_image(confidence, image_bytes, model)
  156. # Créer le lien de téléchargement pour l'image avec les boîtes englobantes
  157. image_download_link = f"http://0.0.0.0:8001/download_image?image_path={urllib.parse.quote(prediction_info.det_image_path)}"
  158. return {
  159. "nb_classe": prediction_info.nb_classe,
  160. "nb_box": prediction_info.nb_box,
  161. "confidence_min": prediction_info.confidence_min,
  162. "pred_classes": prediction_info.pred_classes,
  163. "bbx_coordinates": prediction_info.bbx_coordinates,
  164. "pred_img_id": prediction_info.pred_img_id,
  165. "box_id": prediction_info.box_id,
  166. "diseases_id": prediction_info.diseases_id,
  167. "image_download_link": image_download_link
  168. }
  169. except HTTPException as e:
  170. raise e
  171. except Exception as e:
  172. logger.exception("Une erreur interne est survenue lors de la prédiction d'image.")
  173. raise HTTPException(status_code=500, detail="Une erreur interne est survenue.")
  174. @app.get("/download_image/")
  175. async def download_image(image_path: str):
  176. try:
  177. return FileResponse(image_path)
  178. except Exception as e:
  179. logger.exception("Une erreur est survenue lors du téléchargement de l'image : %s", e)
  180. raise HTTPException(status_code=500, detail="Une erreur interne est survenue lors du téléchargement de l'image.")
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...