Tonic commited on
Commit
9cb381b
·
unverified ·
1 Parent(s): 36e302c

big changes to the application flow

Browse files
Files changed (2) hide show
  1. app.py +30 -131
  2. utils/oneclick.py +67 -105
app.py CHANGED
@@ -1,53 +1,28 @@
1
- from flask import Flask, render_template, request, send_file, jsonify, Response, redirect, url_for
2
  import os
3
- import json
4
  import logging
5
- from utils.callbackmanager import CallbackManager
6
- from utils.generators import (generate_pdf_from_form, generate_pdf_from_meldrx,
7
- analyze_dicom_file_with_ai, analyze_hl7_file_with_ai,
8
- analyze_cda_xml_file_with_ai, analyze_pdf_file_with_ai,
9
- analyze_csv_file_with_ai)
10
- from utils.oneclick import generate_discharge_paper_one_click
11
  from utils.meldrx import MeldRxAPI
 
12
 
13
- # Set up logging
14
  logging.basicConfig(level=logging.INFO)
15
  logger = logging.getLogger(__name__)
16
 
17
  app = Flask(__name__)
18
 
19
- # Set SPACE_URL from environment variable or default to the correct Space URL
 
 
 
20
  SPACE_URL = os.getenv("SPACE_URL", "https://multitransformer-tonic-discharge-guard.hf.space")
21
  REDIRECT_URI = f"{SPACE_URL}/auth/callback"
22
- CALLBACK_MANAGER = CallbackManager(
23
- redirect_uri=REDIRECT_URI,
24
- client_secret=None,
25
- )
26
 
27
- # Mock display_form function for HTML rendering
28
- def display_form(first_name, last_name, middle_initial, dob, age, sex, address, city, state, zip_code,
29
- doctor_first_name, doctor_last_name, doctor_middle_initial, hospital_name, doctor_address,
30
- doctor_city, doctor_state, doctor_zip, admission_date, referral_source, admission_method,
31
- discharge_date, discharge_reason, date_of_death, diagnosis, procedures, medications,
32
- preparer_name, preparer_job_title):
33
- return f"""
34
- <div style='color:#00FFFF; font-family: monospace;'>
35
- <strong>Patient Discharge Form</strong><br>
36
- - Name: {first_name} {middle_initial} {last_name}<br>
37
- - Date of Birth: {dob}, Age: {age}, Sex: {sex}<br>
38
- - Address: {address}, {city}, {state}, {zip_code}<br>
39
- - Doctor: {doctor_first_name} {doctor_middle_initial} {doctor_last_name}<br>
40
- - Hospital/Clinic: {hospital_name}<br>
41
- - Doctor Address: {doctor_address}, {doctor_city}, {doctor_state}, {doctor_zip}<br>
42
- - Admission Date: {admission_date}, Source: {referral_source}, Method: {admission_method}<br>
43
- - Discharge Date: {discharge_date}, Reason: {discharge_reason}<br>
44
- - Date of Death: {date_of_death}<br>
45
- - Diagnosis: {diagnosis}<br>
46
- - Procedures: {procedures}<br>
47
- - Medications: {medications}<br>
48
- - Prepared By: {preparer_name}, {preparer_job_title}
49
- </div>
50
- """
51
 
52
  @app.route('/')
53
  def index():
@@ -55,110 +30,34 @@ def index():
55
 
56
  @app.route('/auth', methods=['GET', 'POST'])
57
  def auth():
58
- auth_url = CALLBACK_MANAGER.get_auth_url()
59
  if request.method == 'POST':
60
- redirected_url = request.form.get('redirected_url')
61
- if redirected_url:
62
- auth_code, error = CALLBACK_MANAGER.handle_callback(redirected_url)
63
- result = CALLBACK_MANAGER.set_auth_code(auth_code) if auth_code else f"<span style='color:#FF4500;'>{error}</span>"
64
- return render_template('auth.html', auth_url=auth_url, auth_result=result)
65
  auth_code = request.form.get('auth_code')
66
  if auth_code:
67
- result = CALLBACK_MANAGER.set_auth_code(auth_code)
68
- return render_template('auth.html', auth_url=auth_url, auth_result=result)
69
- return render_template('auth.html', auth_url=auth_url)
 
70
 
71
  @app.route('/auth/callback', methods=['GET'])
72
  def auth_callback():
73
- redirected_url = request.url
74
- result = CALLBACK_MANAGER.handle_callback(redirected_url)
75
- if "Authentication successful" in result:
76
  return redirect(url_for('dashboard'))
77
- return render_template('auth.html', auth_url=CALLBACK_MANAGER.get_auth_url(), auth_result=result)
78
 
79
  @app.route('/dashboard', methods=['GET'])
80
  def dashboard():
81
- if not CALLBACK_MANAGER.access_token:
82
- return render_template('auth.html', auth_url=CALLBACK_MANAGER.get_auth_url(), auth_result="<span style='color:#FF8C00;'>Please authenticate first.</span>")
83
-
84
- data = CALLBACK_MANAGER.get_patient_data()
85
- if data.startswith('<span'):
86
- return render_template('dashboard.html', error=data)
87
- patients_data = json.loads(data)
88
- patients = [entry['resource'] for entry in patients_data.get('entry', []) if entry['resource'].get('resourceType') == 'Patient']
89
  return render_template('dashboard.html', patients=patients, authenticated=True)
90
 
91
- @app.route('/auth/patient-data', methods=['GET'])
92
- def patient_data():
93
- data = CALLBACK_MANAGER.get_patient_data()
94
- return jsonify(json.loads(data) if data and not data.startswith('<span') else {"error": data})
95
-
96
- @app.route('/auth/pdf', methods=['GET'])
97
- def generate_meldrx_pdf():
98
- patient_data = CALLBACK_MANAGER.get_patient_data()
99
- pdf_path = generate_pdf_from_meldrx(patient_data)
100
- return send_file(pdf_path, as_attachment=True, download_name="meldrx_patient_data.pdf")
101
-
102
- # @app.route('/dashboard', methods=['GET'])
103
- # def dashboard():
104
- # data = CALLBACK_MANAGER.get_patient_data()
105
- # if data.startswith('<span'): # Indicates an error or unauthenticated state
106
- # return render_template('dashboard.html', error=data)
107
- # patients_data = json.loads(data)
108
- # patients = [entry['resource'] for entry in patients_data.get('entry', []) if entry['resource'].get('resourceType') == 'Patient']
109
- # return render_template('dashboard.html', patients=patients, authenticated=True)
110
-
111
- @app.route('/form', methods=['GET', 'POST'])
112
- def discharge_form():
113
- if request.method == 'POST':
114
- form_data = request.form.to_dict()
115
- if 'display' in request.form:
116
- html_form = display_form(**form_data)
117
- return render_template('form.html', form_output=html_form)
118
- elif 'generate_pdf' in request.form:
119
- pdf_path = generate_pdf_from_form(**form_data)
120
- return send_file(pdf_path, as_attachment=True, download_name="discharge_form.pdf")
121
- return render_template('form.html')
122
-
123
- @app.route('/analysis', methods=['GET', 'POST'])
124
- def file_analysis():
125
- if request.method == 'POST':
126
- file = request.files.get('file')
127
- file_type = request.form.get('file_type')
128
- if file:
129
- file_path = os.path.join('/tmp', file.filename)
130
- file.save(file_path)
131
- if file_type == 'dicom':
132
- result = analyze_dicom_file_with_ai(file_path)
133
- elif file_type == 'hl7':
134
- result = analyze_hl7_file_with_ai(file_path)
135
- elif file_type == 'xml' or file_type == 'ccda' or file_type == 'ccd':
136
- result = analyze_cda_xml_file_with_ai(file_path)
137
- elif file_type == 'pdf':
138
- result = analyze_pdf_file_with_ai(file_path)
139
- elif file_type == 'csv':
140
- result = analyze_csv_file_with_ai(file_path)
141
- else:
142
- result = "Unsupported file type"
143
- os.remove(file_path)
144
- return render_template('analysis.html', result=result, file_type=file_type)
145
- return render_template('analysis.html')
146
-
147
- # Configuration from environment variables
148
- CLIENT_ID = os.getenv("MELDRX_CLIENT_ID")
149
- CLIENT_SECRET = None
150
- WORKSPACE_ID = os.getenv("WORKSPACE_URL")
151
-
152
- # # Initialize MeldRx API
153
- # meldrx_api = MeldRxAPI(
154
- # client_id=CLIENT_ID,
155
- # client_secret=CLIENT_SECRET,
156
- # workspace_id=WORKSPACE_ID,
157
- # redirect_uri=REDIRECT_URI
158
- # )
159
  @app.route('/oneclick', methods=['GET', 'POST'])
160
  def one_click():
161
- if not CALLBACK_MANAGER.access_token:
162
  return redirect(url_for('auth'))
163
  if request.method == 'POST':
164
  patient_id = request.form.get('patient_id', '')
@@ -167,12 +66,12 @@ def one_click():
167
  action = request.form.get('action', '')
168
 
169
  pdf_path, status, display_summary = generate_discharge_paper_one_click(
170
- CALLBACK_MANAGER, patient_id, first_name, last_name
171
  )
172
 
173
- if action == "display" and display_summary:
174
  return render_template('oneclick.html', status=status, summary=display_summary)
175
- elif action == "generate_pdf" and pdf_path:
176
  return send_file(pdf_path, as_attachment=True, download_name="discharge_summary.pdf")
177
  return render_template('oneclick.html', status=status, summary=display_summary)
178
 
 
1
+ from flask import Flask, render_template, request, send_file, redirect, url_for
2
  import os
 
3
  import logging
 
 
 
 
 
 
4
  from utils.meldrx import MeldRxAPI
5
+ from utils.oneclick import generate_discharge_paper_one_click
6
 
 
7
  logging.basicConfig(level=logging.INFO)
8
  logger = logging.getLogger(__name__)
9
 
10
  app = Flask(__name__)
11
 
12
+ # Configuration from environment variables
13
+ CLIENT_ID = os.getenv("MELDRX_CLIENT_ID", "04bdc9f9a23d488a868b93d594ee5a4a")
14
+ CLIENT_SECRET = os.getenv("MELDRX_CLIENT_SECRET", None)
15
+ WORKSPACE_ID = os.getenv("MELDRX_WORKSPACE_ID", "09ed4f76-b5ac-42bf-92d5-496933203dbe")
16
  SPACE_URL = os.getenv("SPACE_URL", "https://multitransformer-tonic-discharge-guard.hf.space")
17
  REDIRECT_URI = f"{SPACE_URL}/auth/callback"
 
 
 
 
18
 
19
+ # Initialize MeldRx API
20
+ meldrx_api = MeldRxAPI(
21
+ client_id=CLIENT_ID,
22
+ client_secret=CLIENT_SECRET,
23
+ workspace_id=WORKSPACE_ID,
24
+ redirect_uri=REDIRECT_URI
25
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
  @app.route('/')
28
  def index():
 
30
 
31
  @app.route('/auth', methods=['GET', 'POST'])
32
  def auth():
 
33
  if request.method == 'POST':
 
 
 
 
 
34
  auth_code = request.form.get('auth_code')
35
  if auth_code:
36
+ if meldrx_api.authenticate_with_code(auth_code):
37
+ return redirect(url_for('dashboard'))
38
+ return render_template('auth.html', auth_url=meldrx_api.get_authorization_url(), auth_result="Authentication failed")
39
+ return render_template('auth.html', auth_url=meldrx_api.get_authorization_url())
40
 
41
  @app.route('/auth/callback', methods=['GET'])
42
  def auth_callback():
43
+ auth_code = request.args.get('code')
44
+ if auth_code and meldrx_api.authenticate_with_code(auth_code):
 
45
  return redirect(url_for('dashboard'))
46
+ return render_template('auth.html', auth_url=meldrx_api.get_authorization_url(), auth_result="Callback failed")
47
 
48
  @app.route('/dashboard', methods=['GET'])
49
  def dashboard():
50
+ if not meldrx_api.access_token:
51
+ return redirect(url_for('auth'))
52
+ patients_data = meldrx_api.get_patients()
53
+ if not patients_data or "entry" not in patients_data:
54
+ return render_template('dashboard.html', error="Failed to fetch patient data")
55
+ patients = [entry['resource'] for entry in patients_data.get('entry', [])]
 
 
56
  return render_template('dashboard.html', patients=patients, authenticated=True)
57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  @app.route('/oneclick', methods=['GET', 'POST'])
59
  def one_click():
60
+ if not meldrx_api.access_token:
61
  return redirect(url_for('auth'))
62
  if request.method == 'POST':
63
  patient_id = request.form.get('patient_id', '')
 
66
  action = request.form.get('action', '')
67
 
68
  pdf_path, status, display_summary = generate_discharge_paper_one_click(
69
+ meldrx_api, patient_id, first_name, last_name
70
  )
71
 
72
+ if action == "Display Summary" and display_summary:
73
  return render_template('oneclick.html', status=status, summary=display_summary)
74
+ elif action == "Generate PDF" and pdf_path:
75
  return send_file(pdf_path, as_attachment=True, download_name="discharge_summary.pdf")
76
  return render_template('oneclick.html', status=status, summary=display_summary)
77
 
utils/oneclick.py CHANGED
@@ -1,67 +1,46 @@
1
  import os
2
- import json
3
  import logging
4
- from typing import Optional, Dict, Any
5
  from huggingface_hub import InferenceClient
6
  from utils.meldrx import MeldRxAPI
7
  from utils.pdfutils import PDFGenerator
 
8
  from datetime import datetime
9
 
10
- # Set up logging
11
  logging.basicConfig(level=logging.INFO)
12
  logger = logging.getLogger(__name__)
13
 
14
- # Initialize Hugging Face Inference Client
15
  HF_TOKEN = os.getenv("HF_TOKEN")
16
  if not HF_TOKEN:
17
- raise ValueError("HF_TOKEN environment variable not set. Please set your Hugging Face API token.")
18
  client = InferenceClient(api_key=HF_TOKEN)
19
- MODEL_NAME = "meta-llama/Llama-3.3-70B-Instruct" # Model to use for discharge summary generation
20
 
21
- def generate_ai_discharge_summary(patient_data: Dict[str, Any]) -> Optional[str]:
22
- """
23
- Generate a discharge summary using the Hugging Face Inference Client based on patient data.
24
-
25
- Args:
26
- patient_data (Dict[str, Any]): Patient data in FHIR JSON format.
27
-
28
- Returns:
29
- Optional[str]: Generated discharge summary text or None if generation fails.
30
- """
31
  try:
32
- # Extract relevant patient information
33
- name = patient_data.get("name", [{}])[0]
34
- full_name = f"{name.get('given', ['Unknown'])[0]} {name.get('family', 'Unknown')}"
35
- gender = patient_data.get("gender", "Unknown").capitalize()
36
- birth_date = patient_data.get("birthDate", "Unknown")
37
- age = calculate_age(birth_date) if birth_date != "Unknown" else "Unknown"
38
-
39
- # Placeholder for additional clinical data (e.g., diagnosis, treatment)
40
- # In a real scenario, this would come from related FHIR resources like Encounter, Condition, etc.
41
  patient_info = (
42
- f"Patient Name: {full_name}\n"
43
- f"Gender: {gender}\n"
44
- f"Age: {age}\n\n"
45
- f"Presentation and Diagnosis:\n[Diagnosis data not provided in this snippet; assumed from related FHIR resources]\n\n"
46
- f"Hospital Course:\n[Treatment data not provided in this snippet; assumed from related FHIR resources]\n\n"
47
- f"Outcome:\n[Outcome data not provided in this snippet; assumed from related FHIR resources]"
 
 
 
48
  )
49
 
50
- # Define the prompt for the AI model
51
  messages = [
52
- {"role": "user", "content": ""},
53
  {
54
  "role": "assistant",
55
  "content": (
56
- "You are a senior expert medical health practitioner known for producing discharge papers. "
57
- "You will receive patient information and treatment details. Produce a complete discharge summary "
58
- "based on the information provided."
59
  )
60
  },
61
  {"role": "user", "content": patient_info}
62
  ]
63
 
64
- # Generate discharge summary using streaming
65
  stream = client.chat.completions.create(
66
  model=MODEL_NAME,
67
  messages=messages,
@@ -83,92 +62,75 @@ def generate_ai_discharge_summary(patient_data: Dict[str, Any]) -> Optional[str]
83
  logger.error(f"Error generating AI discharge summary: {str(e)}")
84
  return None
85
 
86
- def calculate_age(birth_date: str) -> str:
87
- """
88
- Calculate age from birth date.
89
-
90
- Args:
91
- birth_date (str): Birth date in YYYY-MM-DD format.
92
-
93
- Returns:
94
- str: Calculated age or 'Unknown' if calculation fails.
95
- """
96
- try:
97
- birth = datetime.strptime(birth_date, "%Y-%m-%d")
98
- today = datetime.today()
99
- age = today.year - birth.year - ((today.month, today.day) < (birth.month, birth.day))
100
- return str(age)
101
- except ValueError:
102
- return "Unknown"
103
-
104
  def generate_discharge_paper_one_click(
105
  meldrx_api: MeldRxAPI,
106
  patient_id: str = None,
107
  first_name: str = None,
108
  last_name: str = None
109
- ) -> tuple[Optional[str], str]:
110
- """
111
- Generate a discharge paper with AI content in one click.
112
-
113
- Args:
114
- meldrx_api (MeldRxAPI): Initialized and authenticated MeldRxAPI instance.
115
- patient_id (str, optional): Patient ID to fetch specific patient data.
116
- first_name (str, optional): First name for patient lookup if patient_id is not provided.
117
- last_name (str, optional): Last name for patient lookup if patient_id is not provided.
118
-
119
- Returns:
120
- tuple[Optional[str], str]: (PDF file path, Status message)
121
- """
122
  try:
123
- # Check if already authenticated
124
  if not meldrx_api.access_token:
125
- return None, "Error: Not authenticated. Please authenticate first in the 'Authenticate with MeldRx' tab."
 
 
 
 
 
126
 
127
- # Fetch patient data
 
 
 
 
 
 
128
  if patient_id:
129
- patient_data = meldrx_api.get_patients()
130
- if not patient_data or "entry" not in patient_data:
131
- return None, "Error: Failed to fetch patient data by ID."
132
- patients = [entry["resource"] for entry in patient_data.get("entry", [])]
133
- patient = next((p for p in patients if p.get("id") == patient_id), None)
134
- if not patient:
135
- return None, f"Error: Patient with ID {patient_id} not found."
 
 
 
 
 
 
 
 
 
136
  else:
137
- patient_data = meldrx_api.get_patients()
138
- if not patient_data or "entry" not in patient_data:
139
- return None, "Error: Failed to fetch patient data."
140
- patients = [entry["resource"] for entry in patient_data.get("entry", [])]
141
- if first_name and last_name:
142
- patient = next(
143
- (p for p in patients if
144
- p.get("name", [{}])[0].get("given", [""])[0].lower() == first_name.lower() and
145
- p.get("name", [{}])[0].get("family", "").lower() == last_name.lower()),
146
- None
147
- )
148
- if not patient:
149
- return None, f"Error: Patient with name {first_name} {last_name} not found."
150
- else:
151
- patient = patients[0] if patients else None
152
- if not patient:
153
- return None, "Error: No patients found in the workspace."
154
-
155
- # Generate AI discharge summary
156
- ai_content = generate_ai_discharge_summary(patient)
157
  if not ai_content:
158
- return None, "Error: Failed to generate AI discharge summary."
 
 
 
 
 
 
 
 
 
 
 
 
 
159
 
160
- # Generate PDF
161
  pdf_generator = PDFGenerator()
162
  pdf_path = pdf_generator.generate_pdf_from_text(
163
  ai_content,
164
- f"discharge_summary_{patient.get('id', 'unknown')}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf"
165
  )
166
 
167
  if pdf_path:
168
- return pdf_path, f"Success: Discharge paper generated for {patient.get('name', [{}])[0].get('given', ['Unknown'])[0]} {patient.get('name', [{}])[0].get('family', 'Unknown')}"
169
- else:
170
- return None, "Error: Failed to generate PDF."
171
 
172
  except Exception as e:
173
  logger.error(f"Error in one-click discharge generation: {str(e)}")
174
- return None, f"Error: {str(e)}"
 
1
  import os
 
2
  import logging
3
+ from typing import Optional, Dict, Any, Tuple
4
  from huggingface_hub import InferenceClient
5
  from utils.meldrx import MeldRxAPI
6
  from utils.pdfutils import PDFGenerator
7
+ from utils.responseparser import PatientDataExtractor
8
  from datetime import datetime
9
 
 
10
  logging.basicConfig(level=logging.INFO)
11
  logger = logging.getLogger(__name__)
12
 
 
13
  HF_TOKEN = os.getenv("HF_TOKEN")
14
  if not HF_TOKEN:
15
+ raise ValueError("HF_TOKEN environment variable not set.")
16
  client = InferenceClient(api_key=HF_TOKEN)
17
+ MODEL_NAME = "meta-llama/Llama-3.3-70B-Instruct"
18
 
19
+ def generate_ai_discharge_summary(patient_dict: Dict[str, str]) -> Optional[str]:
 
 
 
 
 
 
 
 
 
20
  try:
 
 
 
 
 
 
 
 
 
21
  patient_info = (
22
+ f"Patient Name: {patient_dict['first_name']} {patient_dict['last_name']}\n"
23
+ f"Gender: {patient_dict['sex']}\n"
24
+ f"Age: {patient_dict['age']}\n"
25
+ f"Date of Birth: {patient_dict['dob']}\n"
26
+ f"Admission Date: {patient_dict['admission_date']}\n"
27
+ f"Discharge Date: {patient_dict['discharge_date']}\n\n"
28
+ f"Diagnosis:\n{patient_dict['diagnosis']}\n\n"
29
+ f"Medications:\n{patient_dict['medications']}\n\n"
30
+ f"Discharge Instructions:\n[Generated based on available data]"
31
  )
32
 
 
33
  messages = [
 
34
  {
35
  "role": "assistant",
36
  "content": (
37
+ "You are a senior medical practitioner tasked with creating discharge summaries. "
38
+ "Generate a complete discharge summary based on the provided patient information."
 
39
  )
40
  },
41
  {"role": "user", "content": patient_info}
42
  ]
43
 
 
44
  stream = client.chat.completions.create(
45
  model=MODEL_NAME,
46
  messages=messages,
 
62
  logger.error(f"Error generating AI discharge summary: {str(e)}")
63
  return None
64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  def generate_discharge_paper_one_click(
66
  meldrx_api: MeldRxAPI,
67
  patient_id: str = None,
68
  first_name: str = None,
69
  last_name: str = None
70
+ ) -> Tuple[Optional[str], str, Optional[str]]:
 
 
 
 
 
 
 
 
 
 
 
 
71
  try:
 
72
  if not meldrx_api.access_token:
73
+ if not meldrx_api.authenticate():
74
+ return None, "Error: Authentication failed. Please authenticate first.", None
75
+
76
+ patient_data = meldrx_api.get_patients()
77
+ if not patient_data or "entry" not in patient_data:
78
+ return None, "Error: Failed to fetch patient data.", None
79
 
80
+ extractor = PatientDataExtractor(patient_data, format_type="json")
81
+ patients = extractor.get_all_patients()
82
+
83
+ if not patients:
84
+ return None, "Error: No patients found in the workspace.", None
85
+
86
+ patient_dict = None
87
  if patient_id:
88
+ for p in patients:
89
+ extractor.set_patient_by_index(patients.index(p))
90
+ if extractor.get_id() == patient_id:
91
+ patient_dict = p
92
+ break
93
+ if not patient_dict:
94
+ return None, f"Error: Patient with ID {patient_id} not found.", None
95
+ elif first_name and last_name:
96
+ patient_dict = next(
97
+ (p for p in patients if
98
+ p["first_name"].lower() == first_name.lower() and
99
+ p["last_name"].lower() == last_name.lower()),
100
+ None
101
+ )
102
+ if not patient_dict:
103
+ return None, f"Error: Patient with name {first_name} {last_name} not found.", None
104
  else:
105
+ patient_dict = patients[0]
106
+
107
+ ai_content = generate_ai_discharge_summary(patient_dict)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  if not ai_content:
109
+ return None, "Error: Failed to generate AI discharge summary.", None
110
+
111
+ display_summary = (
112
+ f"<div style='color:#00FFFF; font-family: monospace;'>"
113
+ f"<strong>Discharge Summary Preview</strong><br>"
114
+ f"- Name: {patient_dict['first_name']} {patient_dict['last_name']}<br>"
115
+ f"- DOB: {patient_dict['dob']}, Age: {patient_dict['age']}, Sex: {patient_dict['sex']}<br>"
116
+ f"- Address: {patient_dict['address']}, {patient_dict['city']}, {patient_dict['state']} {patient_dict['zip_code']}<br>"
117
+ f"- Admission Date: {patient_dict['admission_date']}<br>"
118
+ f"- Discharge Date: {patient_dict['discharge_date']}<br>"
119
+ f"- Diagnosis: {patient_dict['diagnosis']}<br>"
120
+ f"- Medications: {patient_dict['medications']}<br>"
121
+ f"</div>"
122
+ )
123
 
 
124
  pdf_generator = PDFGenerator()
125
  pdf_path = pdf_generator.generate_pdf_from_text(
126
  ai_content,
127
+ f"discharge_summary_{patient_id or 'unknown'}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf"
128
  )
129
 
130
  if pdf_path:
131
+ return pdf_path, f"Success: Discharge paper generated for {patient_dict['first_name']} {patient_dict['last_name']}", display_summary
132
+ return None, "Error: Failed to generate PDF.", display_summary
 
133
 
134
  except Exception as e:
135
  logger.error(f"Error in one-click discharge generation: {str(e)}")
136
+ return None, f"Error: {str(e)}", None