Spaces:
Sleeping
Sleeping
Upload 2 files
Browse files1MODEL_NAME=best_new_EP382.pt12345# Name of the first model (e.g., your original classifier)MODEL_1_NAME=best_88E.pt# Name of the second model (for Tyre/Alloy classification)MODEL_2_NAME=best_TA_377EP.pt
17 unmodified lines18192021222324252627282930313233343536373839404142434445464748495051525354555657582 unmodified lines61626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811917 unmodified lines# --- Configuration ---UPLOAD_FOLDER = 'static/uploads'MODELS_FOLDER = 'models' # New folder for modelsALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}# Load model name from .env file, with a fallback defaultMODEL_NAME = os.getenv('MODEL_NAME', 'best.pt')MODEL_PATH = os.path.join(MODELS_FOLDER, MODEL_NAME)app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDERos.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)os.makedirs(MODELS_FOLDER, exist_ok=True) # Ensure models folder existsos.makedirs('templates', exist_ok=True) # Ensure templates folder exists# --- Determine Device and Load YOLO Model ---# Use CUDA if available, otherwise use CPUdevice = "cuda" if torch.cuda.is_available() else "cpu"print(f"Using device: {device}")# Load the model once when the application starts for efficiency.model = Nonetry:if not os.path.exists(MODEL_PATH):print(f"Error: Model file not found at {MODEL_PATH}")print("Please make sure the model file exists and the MODEL_NAME in your .env file is correct.")else:model = YOLO(MODEL_PATH)model.to(device) # Move model to the selected deviceprint(f"Successfully loaded model '{MODEL_NAME}' on {device}.")except Exception as e:print(f"Error loading YOLO model: {e}")def allowed_file(filename):"""Checks if a file's extension is in the ALLOWED_EXTENSIONS set."""return '.' in filename and \filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS@app.route('/')def home():"""Serve the main HTML page."""2 unmodified lines@app.route('/predict', methods=['POST'])def predict():"""Endpoint to receive an image, run YOLO classification, and return the single best prediction."""if model is None:return jsonify({"error": "Model could not be loaded. Please check server logs."}), 500# 1. --- File Validation ---if 'file' not in request.files:return jsonify({"error": "No file part in the request"}), 400file = request.files['file']if file.filename == '':return jsonify({"error": "No selected file"}), 400if not file or not allowed_file(file.filename):return jsonify({"error": "File type not allowed"}), 400# 2. --- Save the File Temporarily ---filename = secure_filename(file.filename)filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)file.save(filepath)# 3. --- Perform Inference ---try:# Run the YOLO model on the uploaded image. The model is already on the correct device.results = model(filepath)# 4. --- Process Results to Get ONLY the Top Prediction ---# Get the first result object from the listresult = results[0]# Access the probabilities objectprobs = result.probs# Get the index and confidence of the top predictiontop1_index = probs.top1top1_confidence = float(probs.top1conf) # Convert tensor to Python float# Get the class name from the model's 'names' dictionaryclass_name = model.names[top1_index]# Create the final prediction objectprediction = {"class": class_name,"confidence": top1_confidence}# Return the single prediction object as JSONreturn jsonify(prediction)except Exception as e:return jsonify({"error": f"An error occurred during inference: {str(e)}"}), 500finally:# 5. --- Cleanup ---if os.path.exists(filepath):os.remove(filepath)17 unmodified lines181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889902 unmodified lines9394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015117 unmodified lines# --- Configuration ---UPLOAD_FOLDER = 'static/uploads'MODELS_FOLDER = 'models'ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}# --- NEW: Load model names from .env file, with fallback defaults ---MODEL_1_NAME = os.getenv('MODEL_1_NAME', 'best.pt')MODEL_2_NAME = os.getenv('MODEL_2_NAME', 'tyre_alloy.pt') # New model for Tyre/AlloyMODEL_1_PATH = os.path.join(MODELS_FOLDER, MODEL_1_NAME)MODEL_2_PATH = os.path.join(MODELS_FOLDER, MODEL_2_NAME)app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDERos.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)os.makedirs(MODELS_FOLDER, exist_ok=True)os.makedirs('templates', exist_ok=True)# --- Determine Device ---device = "cuda" if torch.cuda.is_available() else "cpu"print(f"Using device: {device}")# --- NEW: Load multiple YOLO Models ---model1, model2 = None, None# Load Model 1try:if not os.path.exists(MODEL_1_PATH):print(f"Warning: Model file not found at {MODEL_1_PATH}")else:model1 = YOLO(MODEL_1_PATH)model1.to(device)print(f"Successfully loaded model '{MODEL_1_NAME}' on {device}.")except Exception as e:print(f"Error loading Model 1 ({MODEL_1_NAME}): {e}")# Load Model 2try:if not os.path.exists(MODEL_2_PATH):print(f"Warning: Model file not found at {MODEL_2_PATH}")else:model2 = YOLO(MODEL_2_PATH)model2.to(device)print(f"Successfully loaded model '{MODEL_2_NAME}' on {device}.")except Exception as e:print(f"Error loading Model 2 ({MODEL_2_NAME}): {e}")def allowed_file(filename):"""Checks if a file's extension is in the ALLOWED_EXTENSIONS set."""return '.' in filename and \filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONSdef run_inference(model, filepath):"""Helper function to run inference and format the result."""if model is None:return None # Return None if the model isn't loadedresults = model(filepath)result = results[0]probs = result.probstop1_index = probs.top1top1_confidence = float(probs.top1conf)class_name = model.names[top1_index]return {"class": class_name,"confidence": top1_confidence}@app.route('/')def home():"""Serve the main HTML page."""2 unmodified lines@app.route('/predict', methods=['POST'])def predict():"""Endpoint to receive an image and run classification based on the requested model type."""# 1. --- File Validation ---if 'file' not in request.files:return jsonify({"error": "No file part in the request"}), 400file = request.files['file']if file.filename == '':return jsonify({"error": "No selected file"}), 400if not file or not allowed_file(file.filename):return jsonify({"error": "File type not allowed"}), 400# --- NEW: Get the model type from the form data ---model_type = request.form.get('model_type', 'model1') # default to model1# 2. --- Save the File Temporarily ---filename = secure_filename(file.filename)filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)file.save(filepath)# 3. --- Perform Inference based on model_type ---try:if model_type == 'model1':if model1 is None:return jsonify({"error": f"Model '{MODEL_1_NAME}' is not loaded. Check server logs."}), 500prediction = run_inference(model1, filepath)return jsonify(prediction)elif model_type == 'model2':if model2 is None:return jsonify({"error": f"Model '{MODEL_2_NAME}' is not loaded. Check server logs."}), 500prediction = run_inference(model2, filepath)return jsonify(prediction)elif model_type == 'combined':if model1 is None or model2 is None:return jsonify({"error": "One or more models required for combined mode are not loaded. Check server logs."}), 500pred1 = run_inference(model1, filepath)pred2 = run_inference(model2, filepath)combined_prediction = {"model1_result": pred1,"model2_result": pred2}return jsonify(combined_prediction)else:return jsonify({"error": "Invalid model type specified"}), 400except Exception as e:return jsonify({"error": f"An error occurred during inference: {str(e)}"}), 500finally:# 4. --- Cleanup ---if os.path.exists(filepath):os.remove(filepath)
.env+5-1
app.py+82-50