dhruv2842 commited on
Commit
69c8cf6
Β·
verified Β·
1 Parent(s): 51ab4dd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -27
app.py CHANGED
@@ -5,19 +5,21 @@ import numpy as np
5
  import os
6
  import cv2
7
  import tensorflow as tf
8
- import firebase_admin
9
- from firebase_admin import credentials, db
10
  from datetime import datetime
 
 
11
 
12
  app = Flask(__name__)
13
 
14
- # βœ… 1. Initialize Firebase
15
- cred = credentials.Certificate("glaucoma-4b682-firebase-adminsdk-fbsvc-cd31fbe99d.json") # Path to your service account JSON
16
 
17
- firebase_admin.initialize_app(cred)
18
- # Will save results here
 
 
19
 
20
- # βœ… 2. Load the Model
21
  model = load_model('mobilenet_glaucoma_model.h5', compile=False)
22
 
23
  # βœ… 3. Preprocess Image
@@ -39,8 +41,8 @@ def make_gradcam(img_array, model, last_conv_layer_name='Conv_1_bn'):
39
  grads = tape.gradient(loss, conv_outputs)
40
 
41
  pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2))
42
- conv_outputs = conv_outputs[0].numpy() # βœ… IMPORTANT
43
- pooled_grads = pooled_grads.numpy()
44
 
45
  for i in range(conv_outputs.shape[-1]):
46
  conv_outputs[..., i] *= pooled_grads[i]
@@ -75,16 +77,16 @@ def home():
75
 
76
  @app.route("/test_file")
77
  def test_file():
78
- """Check if the Firebase service account JSON is present and readable."""
79
- filepath = "glaucoma-4b682-firebase-adminsdk-fbsvc-cd31fbe99d.json"
80
  if os.path.exists(filepath):
81
- return f"βœ… Service account file found at: {filepath}"
82
  else:
83
- return "❌ Service account JSON NOT found."
84
 
85
  @app.route('/predict', methods=['POST'])
86
  def predict():
87
- """Perform prediction and save results to Firebase."""
88
  if 'file' not in request.files:
89
  return jsonify({'error': 'No file uploaded'}), 400
90
 
@@ -107,14 +109,16 @@ def predict():
107
  gradcam_filename = f"gradcam_{int(datetime.now().timestamp())}.png"
108
  save_gradcam_image(img, heatmap, filename=gradcam_filename)
109
 
110
- # Save to Firebase
111
- results_ref.push({
112
- 'image_filename': file.filename,
113
- 'prediction': result,
114
- 'confidence': confidence,
115
- 'gradcam_filename': gradcam_filename,
116
- 'timestamp': datetime.now().isoformat()
117
- })
 
 
118
 
119
  return jsonify({
120
  'prediction': result,
@@ -129,11 +133,26 @@ def predict():
129
 
130
  @app.route('/results', methods=['GET'])
131
  def results():
132
- """List all results from the Firebase database."""
133
- results_data = results_ref.get()
134
- if not results_data:
135
- results_data = []
136
- return jsonify(results_data)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
 
138
  @app.route('/gradcam/<filename>')
139
  def get_gradcam(filename):
 
5
  import os
6
  import cv2
7
  import tensorflow as tf
 
 
8
  from datetime import datetime
9
+ import psycopg2
10
+ from psycopg2.extras import DictCursor
11
 
12
  app = Flask(__name__)
13
 
14
+ # βœ… 1. Connect to PostgreSQL (Supabase)
15
+ POSTGRES_URL = "postgresql://postgres.otihqjwfqjwccsipzroy:Dhruvagr%40123@aws-0-us-east-2.pooler.supabase.com:5432/postgres"
16
 
17
+ def get_db_connection():
18
+ """Get a new database connection."""
19
+ conn = psycopg2.connect(POSTGRES_URL)
20
+ return conn
21
 
22
+ # βœ… 2. Load Model
23
  model = load_model('mobilenet_glaucoma_model.h5', compile=False)
24
 
25
  # βœ… 3. Preprocess Image
 
41
  grads = tape.gradient(loss, conv_outputs)
42
 
43
  pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2))
44
+ conv_outputs = conv_outputs[0].numpy()
45
+ pooled_grads = pooled_grads.numpy()
46
 
47
  for i in range(conv_outputs.shape[-1]):
48
  conv_outputs[..., i] *= pooled_grads[i]
 
77
 
78
  @app.route("/test_file")
79
  def test_file():
80
+ """Check if the model file is present and readable."""
81
+ filepath = "mobilenet_glaucoma_model.h5"
82
  if os.path.exists(filepath):
83
+ return f"βœ… Model file found at: {filepath}"
84
  else:
85
+ return "❌ Model file NOT found."
86
 
87
  @app.route('/predict', methods=['POST'])
88
  def predict():
89
+ """Perform prediction and save results to PostgreSQL (Supabase)."""
90
  if 'file' not in request.files:
91
  return jsonify({'error': 'No file uploaded'}), 400
92
 
 
109
  gradcam_filename = f"gradcam_{int(datetime.now().timestamp())}.png"
110
  save_gradcam_image(img, heatmap, filename=gradcam_filename)
111
 
112
+ # Save results to PostgreSQL
113
+ conn = get_db_connection()
114
+ cursor = conn.cursor()
115
+ cursor.execute("""
116
+ INSERT INTO results (image_filename, prediction, confidence, gradcam_filename, timestamp)
117
+ VALUES (%s, %s, %s, %s, %s)
118
+ """, (file.filename, result, confidence, gradcam_filename, datetime.now().isoformat()))
119
+ conn.commit()
120
+ cursor.close()
121
+ conn.close()
122
 
123
  return jsonify({
124
  'prediction': result,
 
133
 
134
  @app.route('/results', methods=['GET'])
135
  def results():
136
+ """List all results from the PostgreSQL database."""
137
+ conn = get_db_connection()
138
+ cursor = conn.cursor(cursor_factory=DictCursor)
139
+ cursor.execute("SELECT * FROM results ORDER BY timestamp DESC")
140
+ results_data = cursor.fetchall()
141
+ cursor.close()
142
+ conn.close()
143
+
144
+ results_list = []
145
+ for record in results_data:
146
+ results_list.append({
147
+ 'id': record['id'], # Assumes 'id' is your primary key column
148
+ 'image_filename': record['image_filename'],
149
+ 'prediction': record['prediction'],
150
+ 'confidence': record['confidence'],
151
+ 'gradcam_filename': record['gradcam_filename'],
152
+ 'timestamp': record['timestamp']
153
+ })
154
+
155
+ return jsonify(results_list)
156
 
157
  @app.route('/gradcam/<filename>')
158
  def get_gradcam(filename):