Raushan2709 commited on
Commit
f177f7b
·
verified ·
1 Parent(s): e9063f1

Upload 5 files

Browse files
Files changed (5) hide show
  1. class_indices.pkl +3 -0
  2. fracture_detection_model.pkl +3 -0
  3. index.html +183 -0
  4. main.py +123 -0
  5. new.py +28 -0
class_indices.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:83b58cbb37e7e8805499e59d9449b182d7cfcc574006075db6e53df072c181c1
3
+ size 151
fracture_detection_model.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c9154619b16f95469b5188f54a0e3d71f0a3737c902a8687738d3fa8044acf32
3
+ size 228494688
index.html ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>X-ray Fracture Detection</title>
7
+ <!-- Tailwind CSS for styling -->
8
+ <script src="https://cdn.tailwindcss.com"></script>
9
+ <!-- Inter font from Google Fonts -->
10
+ <link rel="preconnect" href="https://fonts.googleapis.com">
11
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
12
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
13
+ <style>
14
+ body {
15
+ font-family: 'Inter', sans-serif;
16
+ }
17
+ /* Simple spinner animation */
18
+ .loader {
19
+ border: 4px solid #f3f3f3;
20
+ border-radius: 50%;
21
+ border-top: 4px solid #3498db;
22
+ width: 40px;
23
+ height: 40px;
24
+ animation: spin 1s linear infinite;
25
+ }
26
+ @keyframes spin {
27
+ 0% { transform: rotate(0deg); }
28
+ 100% { transform: rotate(360deg); }
29
+ }
30
+ </style>
31
+ </head>
32
+ <body class="bg-gray-100 min-h-screen flex items-center justify-center">
33
+
34
+ <div class="w-full max-w-lg mx-auto bg-white rounded-xl shadow-lg p-8 md:p-12">
35
+
36
+ <!-- Header -->
37
+ <div class="text-center mb-8">
38
+ <h1 class="text-3xl font-bold text-gray-800">Fracture Detection AI</h1>
39
+ <p class="text-gray-500 mt-2">Upload an X-ray image to check for fractures.</p>
40
+ </div>
41
+
42
+ <!-- File Upload Section -->
43
+ <div>
44
+ <!-- Styled file input -->
45
+ <label for="file-upload" class="w-full cursor-pointer bg-gray-200 text-gray-700 font-semibold py-3 px-4 rounded-lg inline-flex items-center justify-center hover:bg-gray-300 transition duration-300">
46
+ <svg class="w-6 h-6 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"></path></svg>
47
+ <span id="file-label">Select an X-ray Image</span>
48
+ </label>
49
+ <input id="file-upload" type="file" class="hidden" accept="image/*">
50
+ </div>
51
+
52
+ <!-- Image Preview -->
53
+ <div id="image-preview-container" class="mt-6 text-center hidden">
54
+ <p class="text-sm font-medium text-gray-600 mb-2">Image Preview:</p>
55
+ <img id="image-preview" src="#" alt="Image preview" class="max-w-xs mx-auto rounded-lg shadow-md"/>
56
+ </div>
57
+
58
+ <!-- Predict Button -->
59
+ <div class="mt-8">
60
+ <button id="predict-button" class="w-full bg-blue-600 text-white font-bold py-3 px-4 rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-4 focus:ring-blue-300 transition duration-300 disabled:bg-gray-400 disabled:cursor-not-allowed" disabled>
61
+ Upload & Predict
62
+ </button>
63
+ </div>
64
+
65
+ <!-- Results Section -->
66
+ <div id="results" class="mt-8 text-center hidden">
67
+ <!-- Spinner -->
68
+ <div id="loader" class="loader mx-auto hidden"></div>
69
+ <!-- Result Text -->
70
+ <div id="result-text" class="mt-4 p-4 rounded-lg"></div>
71
+ </div>
72
+
73
+ <!-- Error Message -->
74
+ <div id="error-message" class="mt-6 text-center text-red-600 font-semibold hidden"></div>
75
+
76
+ </div>
77
+
78
+ <script>
79
+ const fileUpload = document.getElementById('file-upload');
80
+ const fileLabel = document.getElementById('file-label');
81
+ const imagePreviewContainer = document.getElementById('image-preview-container');
82
+ const imagePreview = document.getElementById('image-preview');
83
+ const predictButton = document.getElementById('predict-button');
84
+ const resultsDiv = document.getElementById('results');
85
+ const resultText = document.getElementById('result-text');
86
+ const loader = document.getElementById('loader');
87
+ const errorMessage = document.getElementById('error-message');
88
+
89
+ let selectedFile = null;
90
+
91
+ // Listen for file selection
92
+ fileUpload.addEventListener('change', (event) => {
93
+ selectedFile = event.target.files[0];
94
+ if (selectedFile) {
95
+ // Update label text
96
+ fileLabel.textContent = selectedFile.name;
97
+
98
+ // Show image preview
99
+ const reader = new FileReader();
100
+ reader.onload = (e) => {
101
+ imagePreview.src = e.target.result;
102
+ imagePreviewContainer.classList.remove('hidden');
103
+ };
104
+ reader.readAsDataURL(selectedFile);
105
+
106
+ // Enable predict button
107
+ predictButton.disabled = false;
108
+
109
+ // Reset previous results
110
+ resultsDiv.classList.add('hidden');
111
+ errorMessage.classList.add('hidden');
112
+ }
113
+ });
114
+
115
+ // Listen for predict button click
116
+ predictButton.addEventListener('click', async () => {
117
+ if (!selectedFile) return;
118
+
119
+ // Prepare for API call
120
+ const formData = new FormData();
121
+ formData.append('file', selectedFile);
122
+
123
+ // Show loading spinner and hide previous results
124
+ resultsDiv.classList.remove('hidden');
125
+ loader.classList.remove('hidden');
126
+ resultText.classList.add('hidden');
127
+ errorMessage.classList.add('hidden');
128
+ predictButton.disabled = true;
129
+
130
+ try {
131
+ // IMPORTANT: This assumes your FastAPI server is running on http://127.0.0.1:8000
132
+ const response = await fetch('http://127.0.0.1:8000/predict', {
133
+ method: 'POST',
134
+ body: formData,
135
+ });
136
+
137
+ if (!response.ok) {
138
+ const errorData = await response.json();
139
+ throw new Error(errorData.detail || `Server error: ${response.statusText}`);
140
+ }
141
+
142
+ const data = await response.json();
143
+
144
+ // Display the result
145
+ displayResult(data);
146
+
147
+ } catch (error) {
148
+ // Display error message
149
+ console.error('Error:', error);
150
+ errorMessage.textContent = `Error: Could not connect to the API or the file is invalid. Make sure the server is running. Details: ${error.message}`;
151
+ errorMessage.classList.remove('hidden');
152
+ resultsDiv.classList.add('hidden');
153
+ } finally {
154
+ // Hide loader and re-enable button
155
+ loader.classList.add('hidden');
156
+ predictButton.disabled = false;
157
+ }
158
+ });
159
+
160
+ function displayResult(data) {
161
+ const prediction = data.prediction;
162
+ const confidence = parseFloat(data.confidence) * 100;
163
+
164
+ // Clear previous styles
165
+ resultText.classList.remove('bg-green-100', 'text-green-800', 'bg-red-100', 'text-red-800', 'bg-yellow-100', 'text-yellow-800');
166
+
167
+ let resultHTML = `<p class="text-xl font-bold">Prediction: <span class="capitalize">${prediction}</span></p>
168
+ <p class="text-md mt-1">Confidence: ${confidence.toFixed(2)}%</p>`;
169
+
170
+ // Style based on prediction
171
+ if (prediction.toLowerCase().includes('fracture')) {
172
+ resultText.classList.add('bg-red-100', 'text-red-800');
173
+ } else {
174
+ resultText.classList.add('bg-green-100', 'text-green-800');
175
+ }
176
+
177
+ resultText.innerHTML = resultHTML;
178
+ resultText.classList.remove('hidden');
179
+ }
180
+
181
+ </script>
182
+ </body>
183
+ </html>
main.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import fastapi
2
+ from fastapi import File, UploadFile, HTTPException
3
+ from fastapi.middleware.cors import CORSMiddleware # Added for frontend communication
4
+ import uvicorn
5
+ import pickle
6
+ import numpy as np
7
+ import tensorflow as tf
8
+ from PIL import Image
9
+ import io
10
+ import os
11
+
12
+ # --- Basic FastAPI App Setup ---
13
+ app = fastapi.FastAPI(
14
+ title="X-ray Fracture Detection API",
15
+ description="An API to predict bone fractures from X-ray images.",
16
+ version="1.0.0"
17
+ )
18
+
19
+ # --- CORS (Cross-Origin Resource Sharing) Middleware ---
20
+ # This is the new section that fixes the "Failed to fetch" error.
21
+ # It allows your HTML frontend to communicate with this Python backend.
22
+ app.add_middleware(
23
+ CORSMiddleware,
24
+ allow_origins=["*"], # Allows all origins
25
+ allow_credentials=True,
26
+ allow_methods=["*"], # Allows all methods (GET, POST, etc.)
27
+ allow_headers=["*"], # Allows all headers
28
+ )
29
+
30
+ # --- Loading the Model and Class Indices ---
31
+ # Note: Ensure these .pkl files are in the same directory as this script.
32
+ MODEL_PATH = 'fracture_detection_model.pkl'
33
+ CLASS_INDICES_PATH = 'class_indices.pkl'
34
+
35
+ # Check if model files exist before loading
36
+ if not os.path.exists(MODEL_PATH) or not os.path.exists(CLASS_INDICES_PATH):
37
+ raise RuntimeError(f"Model or class indices files not found. Please ensure '{MODEL_PATH}' and '{CLASS_INDICES_PATH}' are in the correct directory.")
38
+
39
+ # Load the trained model
40
+ try:
41
+ with open(MODEL_PATH, 'rb') as f:
42
+ model = pickle.load(f)
43
+ except Exception as e:
44
+ raise RuntimeError(f"Error loading the model: {e}")
45
+
46
+ # Load the class indices
47
+ try:
48
+ with open(CLASS_INDICES_PATH, 'rb') as f:
49
+ class_indices = pickle.load(f)
50
+ # Invert the dictionary to map index to class name
51
+ class_names = {v: k for k, v in class_indices.items()}
52
+ except Exception as e:
53
+ raise RuntimeError(f"Error loading class indices: {e}")
54
+
55
+ print("--- Model and class indices loaded successfully! ---")
56
+
57
+ # --- Image Preprocessing Function ---
58
+ def preprocess_image(image_bytes: bytes, target_size=(150, 150)) -> np.ndarray:
59
+ """
60
+ Preprocesses the uploaded image to match the model's input requirements.
61
+ """
62
+ try:
63
+ # Open the image from bytes
64
+ img = Image.open(io.BytesIO(image_bytes))
65
+
66
+ # Ensure image is in RGB format
67
+ if img.mode != "RGB":
68
+ img = img.convert("RGB")
69
+
70
+ # Resize the image
71
+ img = img.resize(target_size)
72
+
73
+ # Convert image to numpy array and scale pixel values
74
+ img_array = tf.keras.preprocessing.image.img_to_array(img)
75
+ img_array = img_array / 255.0
76
+
77
+ # Expand dimensions to create a batch of 1
78
+ img_batch = np.expand_dims(img_array, axis=0)
79
+ return img_batch
80
+ except Exception as e:
81
+ # Raise an HTTPException for bad image data
82
+ raise HTTPException(status_code=400, detail=f"Image preprocessing failed: {e}")
83
+
84
+
85
+ # --- Prediction Endpoint ---
86
+ @app.post("/predict")
87
+ async def predict(file: UploadFile = File(...)):
88
+ """
89
+ Accepts an X-ray image file and returns the predicted fracture type.
90
+ """
91
+ # 1. Read the image file uploaded by the user
92
+ image_bytes = await file.read()
93
+
94
+ # 2. Preprocess the image to prepare it for the model
95
+ processed_image = preprocess_image(image_bytes)
96
+
97
+ # 3. Make a prediction using the loaded model
98
+ prediction = model.predict(processed_image)
99
+
100
+ # 4. Process the prediction result
101
+ # Find the index of the highest probability
102
+ predicted_index = np.argmax(prediction[0])
103
+ # Get the corresponding class name
104
+ predicted_class = class_names[predicted_index]
105
+ # Get the confidence score
106
+ confidence = float(prediction[0][predicted_index])
107
+
108
+ # 5. Return the result in a JSON format
109
+ return {
110
+ "prediction": predicted_class,
111
+ "confidence": f"{confidence:.2f}"
112
+ }
113
+
114
+ # --- Root Endpoint ---
115
+ @app.get("/")
116
+ def read_root():
117
+ return {"message": "Welcome to the Fracture Detection API. Please use the /docs endpoint for more information."}
118
+
119
+ # --- To run this application ---
120
+ # 1. Install necessary libraries: pip install fastapi "uvicorn[standard]" tensorflow numpy Pillow python-multipart
121
+ # 2. Save your .pkl files in the same directory as this script.
122
+ # 3. Run from your terminal: uvicorn main:app --reload
123
+
new.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pickle
2
+
3
+ # Define the path to your pickle file
4
+ file_path = 'class_indices.pkl'
5
+
6
+ try:
7
+ # Open the file in binary read mode ('rb')
8
+ with open(file_path, 'rb') as f:
9
+ # Load the data from the file
10
+ class_indices = pickle.load(f)
11
+
12
+ # The number of classes is the length of the dictionary/list
13
+ num_classes = len(class_indices)
14
+
15
+ print(f"✅ Found {num_classes} classes in '{file_path}'.")
16
+
17
+ # Optional: Print the first 5 class mappings to see what they look like
18
+ if isinstance(class_indices, dict):
19
+ print("\nHere are a few examples:")
20
+ for i, (class_name, index) in enumerate(class_indices.items()):
21
+ if i >= 5:
22
+ break
23
+ print(f" - '{class_name}': {index}")
24
+
25
+ except FileNotFoundError:
26
+ print(f"❌ Error: The file '{file_path}' was not found.")
27
+ except Exception as e:
28
+ print(f"An error occurred: {e}")