SERHANI commited on
Commit
436eabd
·
verified ·
1 Parent(s): 1df36b8

Update index.py

Browse files
Files changed (1) hide show
  1. index.py +65 -43
index.py CHANGED
@@ -1,51 +1,73 @@
 
1
  from ultralytics import YOLO
2
- from flask import Flask, request, jsonify
3
- from PIL import Image, ImageDraw
4
  import io
 
 
 
5
 
6
- app = Flask(__name__)
7
- model = YOLO('last.pt') # Load your YOLO model
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  class_names = ['Acne', 'Dark circles', 'blackheads', 'eczema', 'rosacea', 'whiteheads', 'wrinkles']
9
 
10
- @app.route('/classify', methods=['POST'])
11
- def classify_image():
12
- if 'image' not in request.files:
13
- return jsonify({"error": "No image provided"}), 400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
- file = request.files['image']
16
- if file.filename == '':
17
- return jsonify({"error": "Empty image file"}), 400
 
18
 
19
- image = Image.open(io.BytesIO(file.read()))
20
- resized_image = image.copy()
21
- resized_image.thumbnail((640, 640))
 
 
 
 
 
 
 
 
 
 
 
22
 
23
- # Get results from the model
24
-
25
- results = model(resized_image)[0]
26
-
27
- predictions = []
28
-
29
- if results.boxes is not None:
30
- boxes = results.boxes.xyxy
31
- confidences = results.boxes.conf
32
- classes = results.boxes.cls
33
-
34
- for i in range(len(boxes)):
35
- box = boxes[i]
36
- confidence = confidences[i].item()
37
- class_id = int(classes[i].item())
38
- prediction = {
39
- "x1": box[0].item(),
40
- "y1": box[1].item(),
41
- "x2": box[2].item(),
42
- "y2": box[3].item(),
43
- "confidence": confidence,
44
- "class": class_names[class_id],
45
- }
46
- predictions.append(prediction)
47
-
48
- return jsonify({"predictions": predictions})
49
-
50
- if __name__ == '__main__':
51
- app.run(host='127.0.0.1', port=5000, debug=True)
 
1
+ from fastapi import FastAPI, File, UploadFile, HTTPException
2
  from ultralytics import YOLO
3
+ from PIL import Image
 
4
  import io
5
+ from typing import List
6
+ from pydantic import BaseModel
7
+ import uvicorn
8
 
9
+ # Define the response model
10
+ class Prediction(BaseModel):
11
+ x1: float
12
+ y1: float
13
+ x2: float
14
+ y2: float
15
+ confidence: float
16
+ class_name: str
17
+
18
+ class PredictionResponse(BaseModel):
19
+ predictions: List[Prediction]
20
+
21
+ # Initialize FastAPI app and model
22
+ app = FastAPI(title="Skin Condition Detection API")
23
+ model = YOLO('best.pt')
24
  class_names = ['Acne', 'Dark circles', 'blackheads', 'eczema', 'rosacea', 'whiteheads', 'wrinkles']
25
 
26
+ @app.post("/classify", response_model=PredictionResponse)
27
+ async def classify_image(file: UploadFile = File(...)):
28
+ """
29
+ Endpoint to classify skin conditions in an uploaded image
30
+ """
31
+ # Validate file
32
+ if not file.content_type.startswith("image/"):
33
+ raise HTTPException(status_code=400, detail="File must be an image")
34
+
35
+ try:
36
+ # Read and process image
37
+ contents = await file.read()
38
+ image = Image.open(io.BytesIO(contents))
39
+ resized_image = image.copy()
40
+ resized_image.thumbnail((640, 640))
41
+
42
+ # Get predictions
43
+ results = model(resized_image)[0]
44
+ predictions = []
45
 
46
+ if results.boxes is not None:
47
+ boxes = results.boxes.xyxy
48
+ confidences = results.boxes.conf
49
+ classes = results.boxes.cls
50
 
51
+ for i in range(len(boxes)):
52
+ box = boxes[i]
53
+ confidence = confidences[i].item()
54
+ class_id = int(classes[i].item())
55
+
56
+ prediction = Prediction(
57
+ x1=float(box[0].item()),
58
+ y1=float(box[1].item()),
59
+ x2=float(box[2].item()),
60
+ y2=float(box[3].item()),
61
+ confidence=confidence,
62
+ class_name=class_names[class_id]
63
+ )
64
+ predictions.append(prediction)
65
 
66
+ return PredictionResponse(predictions=predictions)
67
+
68
+ except Exception as e:
69
+ raise HTTPException(status_code=500, detail=str(e))
70
+
71
+ # For local development
72
+ if __name__ == "__main__":
73
+ uvicorn.run(app, host="0.0.0.0", port=7860)