Download model_deployment/app.py from hietraan/Cat_Dog_Detection_using_basic_CNN: direct link, hf CLI and curl.
- Browser
- Download file 1.98 kB
-
https://huggingface.co/hietraan/Cat_Dog_Detection_using_basic_CNN/resolve/main/model_deployment/app.py
- Command line
-
hf download hf://hietraan/Cat_Dog_Detection_using_basic_CNN/model_deployment/app.py
-
curl -L -o app.py https://huggingface.co/hietraan/Cat_Dog_Detection_using_basic_CNN/resolve/main/model_deployment/app.py
1.98 kB
| from flask import Flask, request, render_template | |
| import os | |
| from tensorflow.keras.models import load_model | |
| from tensorflow.keras.preprocessing.image import img_to_array, load_img | |
| import numpy as np | |
| app = Flask(__name__) | |
| # đường dẫn ảnh | |
| UPLOAD_FOLDER = 'static/uploads/' | |
| app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER | |
| # load model | |
| model = load_model('cnn_cats_dogs.h5') | |
| # xử lý ảnh và dự đoán | |
| def detect_img(image_path): | |
| img = load_img(image_path, target_size=(150, 150)) | |
| img_array = img_to_array(img) | |
| # thêm chiều batch | |
| img_array = np.expand_dims(img_array, axis=0) | |
| img_array = img_array / 255.0 | |
| #dự đoán | |
| prediction = model.predict(img_array) | |
| if prediction[0][0] > 0.5: | |
| res = np.round(prediction[0][0] * 100, 2) | |
| return f"Chó {res}%" | |
| else: | |
| res = np.round(100 - prediction[0][0] * 100, 2) | |
| return f"Mèo {res}%" | |
| # trang chủ | |
| def index(): | |
| result = None | |
| image_path = None | |
| if request.method == 'POST': | |
| if 'file' not in request.files: | |
| return 'Không có file nào được tải lên' | |
| file = request.files['file'] | |
| if file.name == '': | |
| return 'Chưa chọn file!' | |
| # lưu ảnh vào thư mục static/uploads | |
| if file: | |
| filename = 'upload_image.jpg' | |
| file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename) | |
| file.save(file_path) | |
| #dự đoán | |
| result = detect_img(file_path) | |
| image_path = f'uploads/{filename}' | |
| return render_template('index.html', result=result, image_path=image_path) | |
| if __name__ == '__main__': | |
| #tạo thư mục uploads nếu chưa có | |
| if not os.path.exists(UPLOAD_FOLDER): | |
| os.makedirs(UPLOAD_FOLDER) | |
| app.run(debug=True, host='0.0.0.0', port=5000) |