|
| 1 | +import torch |
| 2 | +from torchvision import models, transforms |
| 3 | +from flask import Flask, request, jsonify |
| 4 | +from PIL import Image |
| 5 | +import numpy as np |
| 6 | +from io import BytesIO |
| 7 | + |
| 8 | +model = models.detection.fasterrcnn_resnet50_fpn(pretrained=True) |
| 9 | +model.eval() |
| 10 | + |
| 11 | +transform = transforms.Compose([ |
| 12 | + transforms.ToTensor() |
| 13 | +]) |
| 14 | + |
| 15 | +def load_image_from_bytes(image_bytes): |
| 16 | + try: |
| 17 | + img = Image.open(BytesIO(image_bytes)) |
| 18 | + |
| 19 | + if img.format != 'JPEG': |
| 20 | + return None, "Only JPEG images are allowed" |
| 21 | + |
| 22 | + img = np.array(img) |
| 23 | + return img, None |
| 24 | + except Exception as e: |
| 25 | + return None, str(e) |
| 26 | + |
| 27 | +def detect_person(image_np): |
| 28 | + try: |
| 29 | + image_tensor = transform(image_np).unsqueeze(0) |
| 30 | + |
| 31 | + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
| 32 | + model.to(device) |
| 33 | + image_tensor = image_tensor.to(device) |
| 34 | + |
| 35 | + with torch.no_grad(): |
| 36 | + prediction = model(image_tensor) |
| 37 | + |
| 38 | + boxes = prediction[0]['boxes'].cpu().numpy() |
| 39 | + labels = prediction[0]['labels'].cpu().numpy() |
| 40 | + scores = prediction[0]['scores'].cpu().numpy() |
| 41 | + |
| 42 | + detected_people = [] |
| 43 | + |
| 44 | + for i in range(len(scores)): |
| 45 | + if scores[i] > 0.6 and labels[i] == 1: |
| 46 | + confidence = float(scores[i]) * 100 |
| 47 | + detected_people.append({ |
| 48 | + 'confidence': round(confidence, 2), |
| 49 | + 'box': boxes[i].tolist() |
| 50 | + }) |
| 51 | + |
| 52 | + return detected_people, None |
| 53 | + except Exception as e: |
| 54 | + return None, str(e) |
| 55 | + |
| 56 | +app = Flask(__name__) |
| 57 | + |
| 58 | +@app.route('/detect', methods=['POST']) |
| 59 | +def detect(): |
| 60 | + try: |
| 61 | + if 'file' not in request.files: |
| 62 | + return jsonify({"error": "No file part"}), 400 |
| 63 | + |
| 64 | + file = request.files['file'] |
| 65 | + |
| 66 | + if file.filename == '': |
| 67 | + return jsonify({"error": "No selected file"}), 400 |
| 68 | + |
| 69 | + # Проверяем MIME-тип файла |
| 70 | + if file.content_type != 'image/jpeg': |
| 71 | + return jsonify({"error": "Only JPEG images are allowed"}), 400 |
| 72 | + |
| 73 | + image_bytes = file.read() |
| 74 | + |
| 75 | + image_np, error = load_image_from_bytes(image_bytes) |
| 76 | + if image_np is None: |
| 77 | + return jsonify({"error": error}), 400 |
| 78 | + |
| 79 | + detected_people, error = detect_person(image_np) |
| 80 | + if detected_people is None: |
| 81 | + return jsonify({"error": f"Error during detection: {error}"}), 500 |
| 82 | + |
| 83 | + full_path = request.form.get('full_path', None) |
| 84 | + |
| 85 | + if detected_people: |
| 86 | + return jsonify({ |
| 87 | + "message": "Person(s) detected on the image", |
| 88 | + "people": detected_people, |
| 89 | + "full_path": full_path |
| 90 | + }), 200 |
| 91 | + else: |
| 92 | + return jsonify({ |
| 93 | + "message": "No person detected on the image", |
| 94 | + "full_path": full_path |
| 95 | + }), 200 |
| 96 | + |
| 97 | + except Exception as e: |
| 98 | + return jsonify({"error": f"An unexpected error occurred: {str(e)}"}), 500 |
| 99 | + |
| 100 | +if __name__ == '__main__': |
| 101 | + app.run(debug=True, host='0.0.0.0', port=5000, threaded=True) |
0 commit comments