Upload 8 files
Browse filesFiles changed (8)
- .envAdded+3
- DockerfileAdded+39
- app.pyAdded+143
- models/best_new_EP382.ptAdded+3
- models/best_parts_EP336.ptAdded+3
- models/model_summary.txtAdded+16
- processing.pyAdded+83
- requirements.txtAdded+8
123# --- Model Configuration ---
PARTS_MODEL_NAME=best_parts_EP336.pt
DAMAGE_MODEL_NAME=best_new_EP382.pt123456789101112131415161718192021222324252627282930313233343536373839# Use an official Python runtime as a parent image
FROM python:3.10-slim
# Set the working directory in the container
WORKDIR /app
# Install system dependencies for OpenCV and other packages
RUN apt-get update && apt-get install -y \
libgl1-mesa-glx \
libglib2.0-0 \
libsm6 \
libxext6 \
libxrender-dev \
libgomp1 \
&& rm -rf /var/lib/apt/lists/*
# Copy the requirements file
COPY requirements.txt requirements.txt
# Install Python packages
RUN pip install --no-cache-dir -r requirements.txt
# Copy application code
COPY . /app
# Create a non-root user
RUN useradd -m -u 1000 user
# Change ownership
RUN chown -R user:user /app
# Switch to the non-root user
USER user
# Expose the port Gunicorn will run on (Using 7860 as in CMD)
EXPOSE 7860
# Command to run the app
CMD ["python", "app.py", "--host", "0.0.0.0", "--port", "7860"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143import os
import torch
from flask import Flask, request, jsonify, render_template, Response
from flask_cors import CORS
from werkzeug.utils import secure_filename
from ultralytics import YOLO
from dotenv import load_dotenv
import time
import json
import traceback
# Import the processing logic
from processing import process_images
# Load environment variables from .env file
load_dotenv()
app = Flask(__name__)
# Enable CORS for all routes
CORS(app)
# --- Configuration ---
UPLOAD_FOLDER = 'static/uploads'
MODELS_FOLDER = 'models'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}
# --- Load model names from .env file ---
PARTS_MODEL_NAME = os.getenv('PARTS_MODEL_NAME', 'best_parts_EP336.pt')
DAMAGE_MODEL_NAME = os.getenv('DAMAGE_MODEL_NAME', 'best_new_EP382.pt')
# --- Model Paths ---
PARTS_MODEL_PATH = os.path.join(MODELS_FOLDER, PARTS_MODEL_NAME)
DAMAGE_MODEL_PATH = os.path.join(MODELS_FOLDER, DAMAGE_MODEL_NAME)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
os.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}")
# --- Load YOLO Models ---
parts_model, damage_model = None, None
# Load Parts Model
try:
if not os.path.exists(PARTS_MODEL_PATH):
print(f"Warning: Parts model file not found at {PARTS_MODEL_PATH}")
else:
parts_model = YOLO(PARTS_MODEL_PATH)
parts_model.to(device)
print(f"Successfully loaded parts model '{PARTS_MODEL_NAME}' on {device}.")
except Exception as e:
print(f"Error loading Parts Model ({PARTS_MODEL_NAME}): {e}")
# Load Damage Model
try:
if not os.path.exists(DAMAGE_MODEL_PATH):
print(f"Warning: Damage model file not found at {DAMAGE_MODEL_PATH}")
else:
damage_model = YOLO(DAMAGE_MODEL_PATH)
damage_model.to(device)
print(f"Successfully loaded damage model '{DAMAGE_MODEL_NAME}' on {device}.")
except Exception as e:
print(f"Error loading Damage Model ({DAMAGE_MODEL_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_EXTENSIONS
@app.route('/')
def home():
"""Serve the main HTML page."""
return render_template('index.html')
@app.route('/predict', methods=['POST'])
def predict():
"""
Endpoint to receive one or more images, process them immediately,
and return the prediction results.
"""
# 1. --- Get Session Key and Validate ---
# Session key can be used for logging or grouping, but doesn't control logic.
session_key = request.form.get('session_key')
if not session_key:
return jsonify({"error": "No session_key provided in the payload"}), 400
# 2. --- File Validation ---
if 'file' not in request.files:
return jsonify({"error": "No file part in the request"}), 400
files = request.files.getlist('file')
if not files or all(f.filename == '' for f in files):
return jsonify({"error": "No selected files"}), 400
# 3. --- Save Files and Prepare for Processing ---
saved_filepaths = []
for file in files:
if file and allowed_file(file.filename):
# Create a unique filename to prevent overwrites
unique_filename = f"{session_key}_{int(time.time()*1000)}_{secure_filename(file.filename)}"
filepath = os.path.join(app.config['UPLOAD_FOLDER'], unique_filename)
file.save(filepath)
saved_filepaths.append(filepath)
else:
print(f"Skipped invalid file: {file.filename}")
if not saved_filepaths:
return jsonify({"error": "No valid files were uploaded. Allowed types: png, jpg, jpeg"}), 400
# 4. --- Run Prediction ---
try:
print(f"Processing {len(saved_filepaths)} file(s) for session '{session_key}'...")
# This function processes the images and returns the prediction results.
results = process_images(parts_model, damage_model, saved_filepaths)
print(f"Processing complete for session '{session_key}'.")
# Return the results as a JSON response
return Response(json.dumps(results), mimetype='application/json')
except Exception as e:
print(f"An error occurred during processing for session {session_key}: {e}")
traceback.print_exc()
return jsonify({"error": f"An error occurred during processing: {str(e)}"}), 500
finally:
# 5. --- Clean up the saved files ---
for filepath in saved_filepaths:
try:
if os.path.exists(filepath):
os.remove(filepath)
except Exception as e:
print(f"Error cleaning up file {filepath}: {e}")
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7860, debug=True)123version https://git-lfs.github.com/spec/v1oid sha256:9a7d17e7205ca2134f2e416dcf8b072291971fa38e4ef361ad7cc5bd3a34bc0csize 68668535123version https://git-lfs.github.com/spec/v1oid sha256:c31287038cb7d88d40500083a58ca13a35d7f6b9f3e4bfb29a6f9905c2d2f402size 13701458112345678910111213141516best_new_EP382.pt
{0: 'correct', 1: 'incorrect'}
best_parts_EP336.pt
{0: 'alloys',
1: 'dashboard',
2: 'driver_front_side',
3: 'driver_rear_side',
4: 'interior_front',
5: 'passenger_front_side',
6: 'passenger_rear_side',
7: 'service_history',
8: 'tyres'}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283# processing.py
import os
from ultralytics import YOLO
# --- Configuration ---
# These are the specific parts that require a subsequent damage check.
DAMAGE_CHECK_PARTS = {
'driver_front_side',
'driver_rear_side',
'passenger_front_side',
'passenger_rear_side',
}
def run_single_inference(model, filepath):
"""
Helper function to run inference for a single model and format the result.
"""
if model is None:
return None # Return None if the model isn't loaded
results = model(filepath, verbose=False) # verbose=False to keep logs clean
result = results[0]
# Check if it's a classification model with probabilities
if result.probs is not None:
probs = result.probs
top1_index = probs.top1
top1_confidence = float(probs.top1conf)
class_name = model.names[top1_index]
else: # Fallback for detection models or if probs are not available
# Assuming the top prediction is what we need
top1_index = result.boxes.cls[0].int() if len(result.boxes) > 0 else 0
top1_confidence = float(result.boxes.conf[0]) if len(result.boxes) > 0 else 0.0
class_name = model.names[top1_index] if len(result.boxes) > 0 else "unknown"
return {
"class": class_name,
"confidence": round(top1_confidence, 4)
}
def process_images(parts_model, damage_model, image_paths):
"""
Processes a list of images.
1. Runs the 'parts_model' on every image.
2. If the detected part is in DAMAGE_CHECK_PARTS, it then runs the 'damage_model'.
3. Otherwise, the damage status defaults to 'correct'.
"""
if parts_model is None or damage_model is None:
raise RuntimeError("One or more models are not loaded. Check server logs.")
final_results = []
for filepath in image_paths:
filename = os.path.basename(filepath)
print(f"Processing {filename}...")
# 1. First, predict the part
part_prediction = run_single_inference(parts_model, filepath)
predicted_part = part_prediction.get("class") if part_prediction else "unknown"
damage_prediction = None
# 2. Conditionally predict the damage
if predicted_part in DAMAGE_CHECK_PARTS:
print(f" -> Part '{predicted_part}' requires damage check. Running damage model...")
damage_prediction = run_single_inference(damage_model, filepath)
else:
print(f" -> Part '{predicted_part}' does not require damage check. Defaulting to 'correct'.")
# 3. For other parts, default to 'correct'
damage_prediction = {
"class": "correct",
"confidence": 1.0,
"note": "Result by default, not by model inference."
}
# Assemble the final result for this image
final_results.append({
"filename": filename,
"part_prediction": part_prediction,
"damage_prediction": damage_prediction
})
return final_results12345678Flask==3.1.1
flask_cors==5.0.1
python-dotenv==1.1.0
torch
ultralytics==8.3.151
Werkzeug==3.1.3
opencv-python-headless==4.10.0.84
psycopg2-binary==2.9.10.envAdded+3
DockerfileAdded+39
app.pyAdded+143
models/best_new_EP382.ptAdded+3
models/best_parts_EP336.ptAdded+3
models/model_summary.txtAdded+16
processing.pyAdded+83
requirements.txtAdded+8