itsLu commited on
Commit
00a6594
·
1 Parent(s): 7156c2e

Add debug logging and alpha channel fix

Browse files
Files changed (1) hide show
  1. app.py +37 -20
app.py CHANGED
@@ -5,72 +5,89 @@ from tensorflow.keras.preprocessing import image
5
  import numpy as np
6
  from PIL import Image
7
  import io
 
8
 
9
- # Initialize Flask with standard folders
10
  app = Flask(__name__, template_folder='templates', static_folder='static')
11
 
12
- # 1. Load Model
13
  MODEL_PATH = 'model.h5'
14
  try:
15
- model = load_model(MODEL_PATH)
16
- print("Model loaded successfully!")
 
17
  except Exception as e:
18
- print(f"Error loading model: {e}")
19
 
20
  CLASS_NAMES = ['NonDemented', 'VeryMildDemented', 'MildDemented', 'ModerateDemented']
21
 
22
  def prepare_image(img_bytes):
23
- img = Image.open(io.BytesIO(img_bytes))
24
- img = img.resize((224, 224))
25
- img_array = image.img_to_array(img)
26
- img_array = np.expand_dims(img_array, axis=0)
27
- img_array = img_array / 255.0
28
- return img_array
 
 
 
 
 
 
 
 
 
 
 
29
 
30
  # --- ROUTES ---
31
 
32
- # 1. Main Page
33
  @app.route('/')
34
  def home():
35
  return render_template('index.html')
36
 
37
- # 2. FIX: Explicitly serve the assets folder
38
  @app.route('/assets/<path:filename>')
39
  def serve_assets(filename):
40
  return send_from_directory('static/assets', filename)
41
 
42
- # 3. FIX: Serve root files (like brain.svg)
43
  @app.route('/<path:filename>')
44
  def serve_root_files(filename):
45
- # Only serve if the file exists in static (avoids crashing on bad links)
46
  if os.path.exists(os.path.join('static', filename)):
47
  return send_from_directory('static', filename)
48
  return "File not found", 404
49
 
50
- # 4. Handle Predictions
51
- # Updated Predict Function - Accepts ANY file name
52
  @app.route('/api/classify', methods=['POST'])
53
  def predict():
54
- # Check if ANY file was uploaded
55
  if not request.files:
56
  return jsonify({'error': 'No file uploaded'}), 400
57
 
58
- # Grab the first file found, regardless of its key name ('file', 'image', 'img', etc.)
59
  file = next(iter(request.files.values()))
60
 
61
  try:
 
 
 
62
  processed_img = prepare_image(file.read())
 
 
63
  prediction = model.predict(processed_img)
 
64
  class_index = np.argmax(prediction)
65
  confidence = float(np.max(prediction))
66
 
 
 
 
67
  result = {
68
- 'class': CLASS_NAMES[class_index],
69
  'confidence': f"{confidence:.2%}"
70
  }
71
  return jsonify(result)
72
 
73
  except Exception as e:
 
 
74
  return jsonify({'error': str(e)}), 500
75
 
76
  if __name__ == '__main__':
 
5
  import numpy as np
6
  from PIL import Image
7
  import io
8
+ import sys # Added for logging
9
 
 
10
  app = Flask(__name__, template_folder='templates', static_folder='static')
11
 
12
+ # 1. Load Model (Safe Mode)
13
  MODEL_PATH = 'model.h5'
14
  try:
15
+ # compile=False prevents crashing if the model was trained on a different TF version
16
+ model = load_model(MODEL_PATH, compile=False)
17
+ print("SUCCESS: Model loaded!", file=sys.stderr)
18
  except Exception as e:
19
+ print(f"CRITICAL ERROR: Failed to load model. {e}", file=sys.stderr)
20
 
21
  CLASS_NAMES = ['NonDemented', 'VeryMildDemented', 'MildDemented', 'ModerateDemented']
22
 
23
  def prepare_image(img_bytes):
24
+ try:
25
+ img = Image.open(io.BytesIO(img_bytes))
26
+
27
+ # FIX 1: Convert to RGB to remove Alpha channel (transparency) if present
28
+ if img.mode != 'RGB':
29
+ img = img.convert('RGB')
30
+
31
+ # FIX 2: Resize
32
+ img = img.resize((224, 224))
33
+
34
+ img_array = image.img_to_array(img)
35
+ img_array = np.expand_dims(img_array, axis=0)
36
+ img_array = img_array / 255.0
37
+ return img_array
38
+ except Exception as e:
39
+ print(f"Error processing image: {e}", file=sys.stderr)
40
+ raise e
41
 
42
  # --- ROUTES ---
43
 
 
44
  @app.route('/')
45
  def home():
46
  return render_template('index.html')
47
 
 
48
  @app.route('/assets/<path:filename>')
49
  def serve_assets(filename):
50
  return send_from_directory('static/assets', filename)
51
 
 
52
  @app.route('/<path:filename>')
53
  def serve_root_files(filename):
 
54
  if os.path.exists(os.path.join('static', filename)):
55
  return send_from_directory('static', filename)
56
  return "File not found", 404
57
 
58
+ # Predict Route (Accepts any file key)
 
59
  @app.route('/api/classify', methods=['POST'])
60
  def predict():
 
61
  if not request.files:
62
  return jsonify({'error': 'No file uploaded'}), 400
63
 
64
+ # Grab the first file
65
  file = next(iter(request.files.values()))
66
 
67
  try:
68
+ # Debug print
69
+ print(f"Received file: {file.filename}", file=sys.stderr)
70
+
71
  processed_img = prepare_image(file.read())
72
+
73
+ print("Image processed. predicting...", file=sys.stderr)
74
  prediction = model.predict(processed_img)
75
+
76
  class_index = np.argmax(prediction)
77
  confidence = float(np.max(prediction))
78
 
79
+ result_class = CLASS_NAMES[class_index]
80
+ print(f"Prediction success: {result_class}", file=sys.stderr)
81
+
82
  result = {
83
+ 'class': result_class,
84
  'confidence': f"{confidence:.2%}"
85
  }
86
  return jsonify(result)
87
 
88
  except Exception as e:
89
+ # This will show up in the Logs tab!
90
+ print(f"PREDICTION CRASHED: {str(e)}", file=sys.stderr)
91
  return jsonify({'error': str(e)}), 500
92
 
93
  if __name__ == '__main__':