Spaces:
Sleeping
Sleeping
Upload 7 files
Browse filesFiles changed (7)
- .envAdded+1
- DockerfileAdded+29
- app.pyAdded+121
- models/best_88E.ptAdded+3
- postman.jsonAdded+44
- requirements.txtAdded+5
- templates/index.htmlAdded+517
1 MODEL_NAME=best_88E.pt1234567891011121314151617181920212223242526272829# Use an official Python runtime as a parent image
FROM python:3.10-slim
# Set the working directory in the container
WORKDIR /app
# 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"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121# app.py
import os
import torch
from flask import Flask, request, jsonify, render_template
from flask_cors import CORS
from werkzeug.utils import secure_filename
from ultralytics import YOLO
from dotenv import load_dotenv
# 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' # New folder for models
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}
# Load model name from .env file, with a fallback default
MODEL_NAME = os.getenv('MODEL_NAME', 'best.pt')
MODEL_PATH = os.path.join(MODELS_FOLDER, MODEL_NAME)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
os.makedirs(MODELS_FOLDER, exist_ok=True) # Ensure models folder exists
os.makedirs('templates', exist_ok=True) # Ensure templates folder exists
# --- Determine Device and Load YOLO Model ---
# Use CUDA if available, otherwise use CPU
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Using device: {device}")
# Load the model once when the application starts for efficiency.
model = None
try:
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 device
print(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."""
return render_template('index.html')
@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"}), 400
file = request.files['file']
if file.filename == '':
return jsonify({"error": "No selected file"}), 400
if 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 list
result = results[0]
# Access the probabilities object
probs = result.probs
# Get the index and confidence of the top prediction
top1_index = probs.top1
top1_confidence = float(probs.top1conf) # Convert tensor to Python float
# Get the class name from the model's 'names' dictionary
class_name = model.names[top1_index]
# Create the final prediction object
prediction = {
"class": class_name,
"confidence": top1_confidence
}
# Return the single prediction object as JSON
return jsonify(prediction)
except Exception as e:
return jsonify({"error": f"An error occurred during inference: {str(e)}"}), 500
finally:
# 5. --- Cleanup ---
if os.path.exists(filepath):
os.remove(filepath)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)123version https://git-lfs.github.com/spec/v1oid sha256:05e883e1d97b5a9c472c7cc8509a311f504342d49943807ae52623f28a03f114size 1369621651234567891011121314151617181920212223242526272829303132333435363738394041424344{
"info": {
"_postman_id": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d",
"name": "NOW Classification API",
"description": "A collection for testing the Flask API that serves a YOLOv8 classification model. The API takes an image file and returns the top predicted classes with their confidence scores.",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"item": [
{
"name": "Predict Image Class",
"request": {
"method": "POST",
"header": [],
"body": {
"mode": "formdata",
"formdata": [
{
"key": "file",
"type": "file",
"description": "The image file (jpg, png, jpeg) to be classified. You must select a file from your computer.",
"src": []
}
]
},
"url": {
"raw": "http://127.0.0.1:5000/predict",
"protocol": "http",
"host": [
"127",
"0",
"0",
"1"
],
"port": "5000",
"path": [
"predict"
]
},
"description": "Upload an image to get its classification predictions. \n\n**Instructions:**\n1. Go to the **Body** tab below.\n2. Make sure **form-data** is selected.\n3. Find the key named `file`.\n4. On the right side of that row, click **Select Files** and choose an image from your computer.\n5. Click **Send**."
},
"response": []
}
]
}12345Flask==3.1.1
python-dotenv==1.1.0
torch==2.3.1+cu118
ultralytics==8.3.105
Werkzeug==3.1.3123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>YOLO Vision AI</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #0f0f23 0%, #1a1a2e 50%, #16213e 100%);
min-height: 100vh;
overflow-x: hidden;
position: relative;
}
/* Animated background particles */
.particles {
position: absolute;
width: 100%;
height: 100%;
overflow: hidden;
z-index: 0;
}
.particle {
position: absolute;
width: 2px;
height: 2px;
background: #00d4ff;
border-radius: 50%;
animation: float 6s ease-in-out infinite;
opacity: 0.6;
}
@keyframes float {
0%, 100% { transform: translateY(0px) rotate(0deg); }
50% { transform: translateY(-20px) rotate(180deg); }
}
.container {
position: relative;
z-index: 1;
max-width: 800px;
margin: 0 auto;
padding: 2rem;
min-height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.header {
text-align: center;
margin-bottom: 3rem;
animation: slideDown 1s ease-out;
}
.title {
font-size: 3.5rem;
font-weight: 700;
background: linear-gradient(45deg, #00d4ff, #ff00ff, #00ff88);
background-size: 200% 200%;
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
animation: gradientShift 3s ease-in-out infinite;
margin-bottom: 1rem;
text-shadow: 0 0 30px rgba(0, 212, 255, 0.5);
}
.subtitle {
font-size: 1.2rem;
color: #a0a0a0;
font-weight: 300;
}
.upload-area {
width: 100%;
max-width: 500px;
min-height: 300px;
border: 2px dashed #00d4ff;
border-radius: 20px;
background: rgba(0, 212, 255, 0.05);
backdrop-filter: blur(10px);
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
cursor: pointer;
transition: all 0.3s ease;
position: relative;
overflow: hidden;
animation: slideUp 1s ease-out 0.3s both;
}
.upload-area:hover {
border-color: #ff00ff;
background: rgba(255, 0, 255, 0.05);
transform: translateY(-5px);
box-shadow: 0 20px 40px rgba(0, 212, 255, 0.2);
}
.upload-area.dragover {
border-color: #00ff88;
background: rgba(0, 255, 136, 0.1);
transform: scale(1.02);
}
.upload-icon {
font-size: 4rem;
color: #00d4ff;
margin-bottom: 1rem;
transition: all 0.3s ease;
}
.upload-area:hover .upload-icon {
color: #ff00ff;
transform: scale(1.1);
}
.upload-text {
color: #ffffff;
font-size: 1.1rem;
margin-bottom: 0.5rem;
font-weight: 500;
}
.upload-subtext {
color: #a0a0a0;
font-size: 0.9rem;
}
.file-input {
display: none;
}
.preview-container {
margin-top: 2rem;
text-align: center;
animation: fadeIn 0.5s ease-out;
}
.preview-image {
max-width: 100%;
max-height: 300px;
border-radius: 15px;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
border: 2px solid #00d4ff;
}
.predict-button {
background: linear-gradient(45deg, #00d4ff, #0099cc);
border: none;
color: white;
padding: 15px 40px;
font-size: 1.1rem;
font-weight: 600;
border-radius: 50px;
cursor: pointer;
margin-top: 1.5rem;
transition: all 0.3s ease;
text-transform: uppercase;
letter-spacing: 1px;
position: relative;
overflow: hidden;
}
.predict-button:hover {
transform: translateY(-2px);
box-shadow: 0 10px 25px rgba(0, 212, 255, 0.4);
background: linear-gradient(45deg, #ff00ff, #cc0099);
}
.predict-button:disabled {
opacity: 0.6;
cursor: not-allowed;
transform: none;
}
.loading {
display: none;
margin-top: 1rem;
}
.spinner {
width: 40px;
height: 40px;
border: 4px solid rgba(0, 212, 255, 0.3);
border-top: 4px solid #00d4ff;
border-radius: 50%;
animation: spin 1s linear infinite;
margin: 0 auto;
}
.result-container {
margin-top: 2rem;
padding: 2rem;
background: rgba(255, 255, 255, 0.05);
backdrop-filter: blur(15px);
border-radius: 20px;
border: 1px solid rgba(0, 212, 255, 0.3);
animation: slideUp 0.5s ease-out;
text-align: center;
}
.result-class {
font-size: 2rem;
font-weight: 700;
color: #00ff88;
margin-bottom: 1rem;
text-transform: uppercase;
letter-spacing: 2px;
}
.result-confidence {
font-size: 1.2rem;
color: #ffffff;
margin-bottom: 0.5rem;
}
.confidence-bar {
width: 100%;
height: 10px;
background: rgba(255, 255, 255, 0.1);
border-radius: 5px;
overflow: hidden;
margin-top: 1rem;
}
.confidence-fill {
height: 100%;
background: linear-gradient(90deg, #00d4ff, #00ff88);
border-radius: 5px;
transition: width 1s ease-out;
animation: pulse 2s ease-in-out infinite;
}
.error {
color: #ff4444;
background: rgba(255, 68, 68, 0.1);
padding: 1rem;
border-radius: 10px;
border: 1px solid #ff4444;
margin-top: 1rem;
}
@keyframes slideDown {
from { opacity: 0; transform: translateY(-50px); }
to { opacity: 1; transform: translateY(0); }
}
@keyframes slideUp {
from { opacity: 0; transform: translateY(50px); }
to { opacity: 1; transform: translateY(0); }
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
@keyframes gradientShift {
0%, 100% { background-position: 0% 50%; }
50% { background-position: 100% 50%; }
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.7; }
}
/* Responsive design */
@media (max-width: 768px) {
.title {
font-size: 2.5rem;
}
.container {
padding: 1rem;
}
.upload-area {
min-height: 250px;
}
}
</style>
</head>
<body>
<div class="particles" id="particles"></div>
<div class="container">
<div class="header">
<h1 class="title">YOLO12 Vision AI</h1>
<p class="subtitle">Advanced Image Classification with Neural Networks</p>
</div>
<div class="upload-area" id="uploadArea">
<div class="upload-icon">🔮</div>
<div class="upload-text">Drop your image here or click to upload</div>
<div class="upload-subtext">Supports PNG, JPG, JPEG formats</div>
<input type="file" id="fileInput" class="file-input" accept=".png,.jpg,.jpeg">
</div>
<div class="preview-container" id="previewContainer" style="display: none;">
<img id="previewImage" class="preview-image" alt="Preview">
<button class="predict-button" id="predictButton">🚀 Analyze Image</button>
</div>
<div class="loading" id="loading">
<div class="spinner"></div>
<p style="color: #00d4ff; margin-top: 1rem;">Processing your image...</p>
</div>
<div class="result-container" id="resultContainer" style="display: none;">
<div class="result-class" id="resultClass"></div>
<div class="result-confidence">
Confidence: <span id="confidencePercentage"></span>
</div>
<div class="confidence-bar">
<div class="confidence-fill" id="confidenceFill"></div>
</div>
</div>
<div class="error" id="errorContainer" style="display: none;"></div>
</div>
<script>
// Create animated particles
function createParticles() {
const particlesContainer = document.getElementById('particles');
const particleCount = 50;
for (let i = 0; i < particleCount; i++) {
const particle = document.createElement('div');
particle.className = 'particle';
particle.style.left = Math.random() * 100 + '%';
particle.style.top = Math.random() * 100 + '%';
particle.style.animationDelay = Math.random() * 6 + 's';
particle.style.animationDuration = (3 + Math.random() * 3) + 's';
particlesContainer.appendChild(particle);
}
}
// Initialize particles
createParticles();
// DOM elements
const uploadArea = document.getElementById('uploadArea');
const fileInput = document.getElementById('fileInput');
const previewContainer = document.getElementById('previewContainer');
const previewImage = document.getElementById('previewImage');
const predictButton = document.getElementById('predictButton');
const loading = document.getElementById('loading');
const resultContainer = document.getElementById('resultContainer');
const errorContainer = document.getElementById('errorContainer');
const resultClass = document.getElementById('resultClass');
const confidencePercentage = document.getElementById('confidencePercentage');
const confidenceFill = document.getElementById('confidenceFill');
let selectedFile = null;
// Upload area click handler
uploadArea.addEventListener('click', () => {
fileInput.click();
});
// File input change handler
fileInput.addEventListener('change', handleFileSelect);
// Drag and drop handlers
uploadArea.addEventListener('dragover', (e) => {
e.preventDefault();
uploadArea.classList.add('dragover');
});
uploadArea.addEventListener('dragleave', () => {
uploadArea.classList.remove('dragover');
});
uploadArea.addEventListener('drop', (e) => {
e.preventDefault();
uploadArea.classList.remove('dragover');
const files = e.dataTransfer.files;
if (files.length > 0) {
handleFile(files[0]);
}
});
// Predict button handler
predictButton.addEventListener('click', predictImage);
function handleFileSelect(e) {
const file = e.target.files[0];
if (file) {
handleFile(file);
}
}
function handleFile(file) {
// Validate file type
const allowedTypes = ['image/png', 'image/jpeg', 'image/jpg'];
if (!allowedTypes.includes(file.type)) {
showError('Please select a valid image file (PNG, JPG, JPEG)');
return;
}
// Validate file size (max 10MB)
if (file.size > 10 * 1024 * 1024) {
showError('File size too large. Please select a file smaller than 10MB.');
return;
}
selectedFile = file;
// Show preview
const reader = new FileReader();
reader.onload = (e) => {
previewImage.src = e.target.result;
previewContainer.style.display = 'block';
hideError();
hideResult();
};
reader.readAsDataURL(file);
}
async function predictImage() {
if (!selectedFile) {
showError('Please select an image first');
return;
}
// Show loading
loading.style.display = 'block';
predictButton.disabled = true;
hideError();
hideResult();
try {
const formData = new FormData();
formData.append('file', selectedFile);
const response = await fetch('/predict', {
method: 'POST',
body: formData
});
const data = await response.json();
if (response.ok) {
showResult(data);
} else {
showError(data.error || 'An error occurred during prediction');
}
} catch (error) {
showError('Failed to connect to the server. Please try again.');
console.error('Error:', error);
} finally {
loading.style.display = 'none';
predictButton.disabled = false;
}
}
function showResult(data) {
resultClass.textContent = data.class;
const confidence = Math.round(data.confidence * 100);
confidencePercentage.textContent = confidence + '%';
confidenceFill.style.width = confidence + '%';
resultContainer.style.display = 'block';
// Add some visual flair
setTimeout(() => {
confidenceFill.style.width = confidence + '%';
}, 100);
}
function showError(message) {
errorContainer.textContent = message;
errorContainer.style.display = 'block';
}
function hideError() {
errorContainer.style.display = 'none';
}
function hideResult() {
resultContainer.style.display = 'none';
}
// Add some interactive effects
document.addEventListener('mousemove', (e) => {
const particles = document.querySelectorAll('.particle');
const x = e.clientX / window.innerWidth;
const y = e.clientY / window.innerHeight;
particles.forEach((particle, index) => {
const speed = (index % 3 + 1) * 0.5;
const newX = x * speed;
const newY = y * speed;
particle.style.transform = `translate(${newX}px, ${newY}px)`;
});
});
</script>
</body>
</html>.envAdded+1
DockerfileAdded+29
app.pyAdded+121
models/best_88E.ptAdded+3
postman.jsonAdded+44
requirements.txtAdded+5
templates/index.htmlAdded+517