-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathecg.py
More file actions
85 lines (71 loc) · 2.71 KB
/
ecg.py
File metadata and controls
85 lines (71 loc) · 2.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
from tensorflow.keras.models import load_model
import cv2
import numpy as np
import requests
from io import BytesIO
from flask import Flask, jsonify, request
from flask_cors import CORS
from groq import Groq
app = Flask(__name__)
CORS(app)
# Load the model
model = load_model(r"C:\Users\Lenovo\Downloads\ecg_model (1).h5")
# Image settings
img_size = 224
class_labels = ["Myocardial Infarction", "History of MI", "Abnormal Heartbeat", "Normal Person"]
# Groq API Key (Ensure this is stored securely in an environment variable)
API_KEY_LLAMA = "cb95a6b8-29ef-4c5c-bd98-3fe6df21c3cd"
# Function to generate Llama response
def generate_llama_response(result, file_path):
predefined_prompt = f"""
You are an ECG Analyzer. You have been provided with an ECG image ({file_path})
and the result: {result}. Possible results include 'Myocardial Infarction',
'History of MI', 'Abnormal Heartbeat', or 'Normal Person'.
Assist the user with their analysis report.
make it short and concise upto 5 lines
"""
client = Groq(api_key=API_KEY_LLAMA)
response = client.chat.completions.create(
messages=[{"role": "user", "content": predefined_prompt}],
model="llama3-8b-8192",
)
return response.choices[0].message.content
# Function to process and predict ECG image
def predict_ecg(image_source):
# Check if the input is a URL
if image_source.startswith("http"):
response = requests.get(image_source)
if response.status_code != 200:
raise ValueError("Failed to fetch image from URL")
image_array = np.asarray(bytearray(response.content), dtype=np.uint8)
img = cv2.imdecode(image_array, cv2.IMREAD_COLOR)
else:
img = cv2.imread(image_source)
if img is None:
raise ValueError("Image not found or invalid file path")
# Preprocess the image
img = cv2.resize(img, (img_size, img_size))
img = img / 255.0
img = img.reshape(1, img_size, img_size, 3)
# Make a prediction
prediction = model.predict(img)
class_index = np.argmax(prediction)
result = class_labels[class_index]
print(f"✅ Prediction: {result}")
return result
# Flask API route
@app.route('/ecg', methods=['POST'])
def model_predict():
data = request.get_json()
if not data or 'file_path' not in data:
return jsonify({"error": "No file path or URL provided"}), 400
file_path = data['file_path']
try:
result = predict_ecg(file_path)
response = generate_llama_response(result, file_path)
return jsonify({"prediction": response})
except Exception as e:
return jsonify({"error": str(e)}), 500
# Run Flask app
if __name__ == '__main__':
app.run(port=8001, host="0.0.0.0")