Tonic commited on
Commit
be39fa4
·
unverified ·
1 Parent(s): 424cc5f

refactor matching algo

Browse files
Files changed (2) hide show
  1. app.py +7 -116
  2. utils/oneclick.py +24 -14
app.py CHANGED
@@ -4,9 +4,9 @@ import os
4
  import logging
5
  from utils.meldrx import MeldRxAPI
6
  from utils.oneclick import generate_discharge_paper_one_click
7
- from huggingface_hub import InferenceClient
8
 
9
- logging.basicConfig(level=logging.INFO)
10
  logger = logging.getLogger(__name__)
11
 
12
  app = Flask(__name__)
@@ -24,12 +24,7 @@ meldrx_api = MeldRxAPI(
24
  redirect_uri=REDIRECT_URI
25
  )
26
 
27
-
28
- HF_TOKEN = os.getenv("HF_TOKEN")
29
- if not HF_TOKEN:
30
- raise ValueError("HF_TOKEN environment variable not set.")
31
- client = InferenceClient(api_key=HF_TOKEN)
32
- MODEL_NAME = "meta-llama/Llama-3.3-70B-Instruct"
33
 
34
  @app.route('/')
35
  def index():
@@ -57,8 +52,10 @@ def dashboard():
57
  return redirect(url_for('auth'))
58
  patients_data = meldrx_api.get_patients()
59
  if not patients_data or "entry" not in patients_data:
 
60
  return render_template('dashboard.html', error="Failed to fetch patient data")
61
  patients = [entry['resource'] for entry in patients_data.get('entry', [])]
 
62
  return render_template('dashboard.html', patients=patients, authenticated=True)
63
 
64
  @app.route('/oneclick', methods=['GET', 'POST'])
@@ -75,7 +72,7 @@ def one_click():
75
  logger.info(f"One-click request - ID: {patient_id}, First: {first_name}, Last: {last_name}, Action: {action}")
76
 
77
  pdf_path, status, basic_summary, ai_summary = generate_discharge_paper_one_click(
78
- meldrx_api, client, patient_id, first_name, last_name
79
  )
80
 
81
  if action == "Display Summary":
@@ -102,110 +99,4 @@ def one_click():
102
 
103
  if __name__ == '__main__':
104
  port = int(os.getenv("PORT", 7860))
105
- app.run(debug=False, host='0.0.0.0', port=port)
106
-
107
-
108
-
109
- # # app.py
110
- # from flask import Flask, render_template, request, send_file, redirect, url_for
111
- # import os
112
- # import logging
113
- # from utils.meldrx import MeldRxAPI
114
- # from utils.oneclick import generate_discharge_paper_one_click
115
- # from xai import Grok # Adjust import based on actual xAI SDK
116
-
117
- # logging.basicConfig(level=logging.DEBUG) # Changed to DEBUG for more detailed logs
118
- # logger = logging.getLogger(__name__)
119
-
120
- # app = Flask(__name__)
121
-
122
- # CLIENT_ID = os.getenv("MELDRX_CLIENT_ID", "04bdc9f9a23d488a868b93d594ee5a4a")
123
- # CLIENT_SECRET = os.getenv("MELDRX_CLIENT_SECRET", None)
124
- # WORKSPACE_ID = os.getenv("MELDRX_WORKSPACE_ID", "09ed4f76-b5ac-42bf-92d5-496933203dbe")
125
- # SPACE_URL = os.getenv("SPACE_URL", "https://multitransformer-tonic-discharge-guard.hf.space")
126
- # REDIRECT_URI = f"{SPACE_URL}/auth/callback"
127
-
128
- # meldrx_api = MeldRxAPI(
129
- # client_id=CLIENT_ID,
130
- # client_secret=CLIENT_SECRET,
131
- # workspace_id=WORKSPACE_ID,
132
- # redirect_uri=REDIRECT_URI
133
- # )
134
-
135
- # # Initialize xAI client
136
- # grok_client = Grok() # Adjust initialization as needed
137
-
138
- # @app.route('/')
139
- # def index():
140
- # return render_template('index.html')
141
-
142
- # @app.route('/auth', methods=['GET', 'POST'])
143
- # def auth():
144
- # if request.method == 'POST':
145
- # auth_code = request.form.get('auth_code')
146
- # if auth_code and meldrx_api.authenticate_with_code(auth_code):
147
- # return redirect(url_for('dashboard'))
148
- # return render_template('auth.html', auth_url=meldrx_api.get_authorization_url(), auth_result="Authentication failed")
149
- # return render_template('auth.html', auth_url=meldrx_api.get_authorization_url())
150
-
151
- # @app.route('/auth/callback', methods=['GET'])
152
- # def auth_callback():
153
- # auth_code = request.args.get('code')
154
- # if auth_code and meldrx_api.authenticate_with_code(auth_code):
155
- # return redirect(url_for('dashboard'))
156
- # return render_template('auth.html', auth_url=meldrx_api.get_authorization_url(), auth_result="Callback failed")
157
-
158
- # @app.route('/dashboard', methods=['GET'])
159
- # def dashboard():
160
- # if not meldrx_api.access_token:
161
- # return redirect(url_for('auth'))
162
- # patients_data = meldrx_api.get_patients()
163
- # if not patients_data or "entry" not in patients_data:
164
- # logger.error("Failed to fetch patient data for dashboard")
165
- # return render_template('dashboard.html', error="Failed to fetch patient data")
166
- # patients = [entry['resource'] for entry in patients_data.get('entry', [])]
167
- # logger.debug(f"Patients for dashboard: {patients}")
168
- # return render_template('dashboard.html', patients=patients, authenticated=True)
169
-
170
- # @app.route('/oneclick', methods=['GET', 'POST'])
171
- # def one_click():
172
- # if not meldrx_api.access_token:
173
- # return redirect(url_for('auth'))
174
-
175
- # if request.method == 'POST':
176
- # patient_id = request.form.get('patient_id', '').strip()
177
- # first_name = request.form.get('first_name', '').strip()
178
- # last_name = request.form.get('last_name', '').strip()
179
- # action = request.form.get('action', '')
180
-
181
- # logger.info(f"One-click request - ID: {patient_id}, First: {first_name}, Last: {last_name}, Action: {action}")
182
-
183
- # pdf_path, status, basic_summary, ai_summary = generate_discharge_paper_one_click(
184
- # meldrx_api, grok_client, patient_id, first_name, last_name
185
- # )
186
-
187
- # if action == "Display Summary":
188
- # return render_template('oneclick.html',
189
- # status=status,
190
- # basic_summary=basic_summary.replace('\n', '<br>') if basic_summary else None,
191
- # ai_summary=ai_summary.replace('\n', '<br>') if ai_summary else None,
192
- # patient_id=patient_id,
193
- # first_name=first_name,
194
- # last_name=last_name)
195
- # elif action == "Generate PDF" and pdf_path:
196
- # return send_file(pdf_path,
197
- # as_attachment=True,
198
- # download_name=f"discharge_summary_{patient_id or 'patient'}.pdf")
199
- # return render_template('oneclick.html',
200
- # status=status,
201
- # basic_summary=basic_summary.replace('\n', '<br>') if basic_summary else None,
202
- # ai_summary=ai_summary.replace('\n', '<br>') if ai_summary else None,
203
- # patient_id=patient_id,
204
- # first_name=first_name,
205
- # last_name=last_name)
206
-
207
- # return render_template('oneclick.html')
208
-
209
- # if __name__ == '__main__':
210
- # port = int(os.getenv("PORT", 7860))
211
- # app.run(debug=False, host='0.0.0.0', port=port)
 
4
  import logging
5
  from utils.meldrx import MeldRxAPI
6
  from utils.oneclick import generate_discharge_paper_one_click
7
+ from xai import Grok # Adjust import based on actual xAI SDK
8
 
9
+ logging.basicConfig(level=logging.DEBUG)
10
  logger = logging.getLogger(__name__)
11
 
12
  app = Flask(__name__)
 
24
  redirect_uri=REDIRECT_URI
25
  )
26
 
27
+ grok_client = Grok() # Adjust initialization as needed
 
 
 
 
 
28
 
29
  @app.route('/')
30
  def index():
 
52
  return redirect(url_for('auth'))
53
  patients_data = meldrx_api.get_patients()
54
  if not patients_data or "entry" not in patients_data:
55
+ logger.error("Failed to fetch patient data for dashboard")
56
  return render_template('dashboard.html', error="Failed to fetch patient data")
57
  patients = [entry['resource'] for entry in patients_data.get('entry', [])]
58
+ logger.debug(f"Patients for dashboard: {patients}")
59
  return render_template('dashboard.html', patients=patients, authenticated=True)
60
 
61
  @app.route('/oneclick', methods=['GET', 'POST'])
 
72
  logger.info(f"One-click request - ID: {patient_id}, First: {first_name}, Last: {last_name}, Action: {action}")
73
 
74
  pdf_path, status, basic_summary, ai_summary = generate_discharge_paper_one_click(
75
+ meldrx_api, grok_client, patient_id, first_name, last_name
76
  )
77
 
78
  if action == "Display Summary":
 
99
 
100
  if __name__ == '__main__':
101
  port = int(os.getenv("PORT", 7860))
102
+ app.run(debug=False, host='0.0.0.0', port=port)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
utils/oneclick.py CHANGED
@@ -77,38 +77,48 @@ def generate_discharge_paper_one_click(
77
  logger.info(f"Found {len(extractor.patients)} patients in the data")
78
 
79
  matching_patients = []
 
 
 
80
  for i in range(len(extractor.patients)):
81
  extractor.set_patient_by_index(i)
82
  patient_data = extractor.get_patient_dict()
83
 
84
- patient_id_from_data = patient_data.get('id', '').strip().lower()
85
- first_name_from_data = patient_data.get('first_name', '').strip().lower()
86
- last_name_from_data = patient_data.get('last_name', '').strip().lower()
 
 
 
87
 
88
- patient_id_input = patient_id.strip().lower()
89
- first_name_input = first_name.strip().lower()
90
- last_name_input = last_name.strip().lower()
91
 
92
- logger.debug(f"Comparing - ID: {patient_id_input} vs {patient_id_from_data}, "
93
- f"First: {first_name_input} vs {first_name_from_data}, "
94
- f"Last: {last_name_input} vs {last_name_from_data}")
95
 
96
  matches = True
97
- if patient_id_input and patient_id_from_data != patient_id_input:
98
  matches = False
99
- if first_name_input and first_name_from_data != first_name_input:
100
  matches = False
101
- if last_name_input and last_name_from_data != last_name_input:
102
  matches = False
103
 
104
  if matches:
105
  matching_patients.append(patient_data)
106
- logger.info(f"Found matching patient: {patient_data.get('id', 'unknown')}")
 
107
 
108
  if not matching_patients:
109
  search_criteria = f"ID: {patient_id or 'N/A'}, First: {first_name or 'N/A'}, Last: {last_name or 'N/A'}"
110
  logger.warning(f"No patients matched criteria: {search_criteria}")
111
- return None, f"No patients found matching criteria: {search_criteria}", None, None
 
 
 
 
112
 
113
  patient_data = matching_patients[0]
114
  logger.info(f"Selected patient data: {patient_data}")
 
77
  logger.info(f"Found {len(extractor.patients)} patients in the data")
78
 
79
  matching_patients = []
80
+ all_patient_ids = []
81
+ all_patient_names = []
82
+
83
  for i in range(len(extractor.patients)):
84
  extractor.set_patient_by_index(i)
85
  patient_data = extractor.get_patient_dict()
86
 
87
+ patient_id_from_data = str(patient_data.get('id', '')).strip().lower()
88
+ first_name_from_data = str(patient_data.get('first_name', '')).strip().lower()
89
+ last_name_from_data = str(patient_data.get('last_name', '')).strip().lower()
90
+
91
+ all_patient_ids.append(patient_id_from_data)
92
+ all_patient_names.append(f"{first_name_from_data} {last_name_from_data}")
93
 
94
+ patient_id_input = str(patient_id).strip().lower()
95
+ first_name_input = str(first_name).strip().lower()
96
+ last_name_input = str(last_name).strip().lower()
97
 
98
+ logger.debug(f"Patient {i}: ID={patient_id_from_data}, Name={first_name_from_data} {last_name_from_data}")
99
+ logger.debug(f"Comparing - Input: ID={patient_id_input}, First={first_name_input}, Last={last_name_input}")
 
100
 
101
  matches = True
102
+ if patient_id_input and patient_id_input != patient_id_from_data:
103
  matches = False
104
+ if first_name_input and first_name_input not in first_name_from_data:
105
  matches = False
106
+ if last_name_input and last_name_input not in last_name_from_data:
107
  matches = False
108
 
109
  if matches:
110
  matching_patients.append(patient_data)
111
+ logger.info(f"Found matching patient: ID={patient_id_from_data}, "
112
+ f"Name={first_name_from_data} {last_name_from_data}")
113
 
114
  if not matching_patients:
115
  search_criteria = f"ID: {patient_id or 'N/A'}, First: {first_name or 'N/A'}, Last: {last_name or 'N/A'}"
116
  logger.warning(f"No patients matched criteria: {search_criteria}")
117
+ logger.info(f"Available patient IDs: {all_patient_ids}")
118
+ logger.info(f"Available patient names: {all_patient_names}")
119
+ return None, (f"No patients found matching criteria: {search_criteria}\n"
120
+ f"Available IDs: {', '.join(all_patient_ids)}\n"
121
+ f"Available Names: {', '.join(all_patient_names)}"), None, None
122
 
123
  patient_data = matching_patients[0]
124
  logger.info(f"Selected patient data: {patient_data}")