File size: 7,731 Bytes
e714a62
09daffd
219df52
09daffd
 
219df52
 
 
fc7ef83
 
d452590
219df52
09daffd
 
 
 
219df52
09daffd
4a78b46
 
 
219df52
4a78b46
219df52
 
09daffd
219df52
 
 
 
 
 
 
09daffd
219df52
 
 
 
 
 
 
 
 
 
 
 
 
09daffd
 
 
 
219df52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e714a62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
219df52
 
 
 
 
 
 
 
 
 
 
e714a62
 
 
 
 
 
 
 
219df52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09daffd
219df52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
212ac2a
219df52
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
from flask import Flask, render_template, request, send_file, jsonify, Response, redirect, url_for
import os
import json
import logging
from utils.callbackmanager import CallbackManager
from utils.generators import (generate_pdf_from_form, generate_pdf_from_meldrx,
                              analyze_dicom_file_with_ai, analyze_hl7_file_with_ai,
                              analyze_cda_xml_file_with_ai, analyze_pdf_file_with_ai,
                              analyze_csv_file_with_ai)
from utils.oneclick import generate_discharge_paper_one_click
from utils.meldrx import MeldRxAPI

# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = Flask(__name__)

# Set SPACE_URL from environment variable or default to the correct Space URL
SPACE_URL = os.getenv("SPACE_URL", "https://multitransformer-tonic-discharge-guard.hf.space")
REDIRECT_URI = f"{SPACE_URL}/auth/callback"
CALLBACK_MANAGER = CallbackManager(
    redirect_uri=REDIRECT_URI,
    client_secret=None,
)

# Mock display_form function for HTML rendering
def display_form(first_name, last_name, middle_initial, dob, age, sex, address, city, state, zip_code,
                 doctor_first_name, doctor_last_name, doctor_middle_initial, hospital_name, doctor_address,
                 doctor_city, doctor_state, doctor_zip, admission_date, referral_source, admission_method,
                 discharge_date, discharge_reason, date_of_death, diagnosis, procedures, medications,
                 preparer_name, preparer_job_title):
    return f"""
    <div style='color:#00FFFF; font-family: monospace;'>
    <strong>Patient Discharge Form</strong><br>
    - Name: {first_name} {middle_initial} {last_name}<br>
    - Date of Birth: {dob}, Age: {age}, Sex: {sex}<br>
    - Address: {address}, {city}, {state}, {zip_code}<br>
    - Doctor: {doctor_first_name} {doctor_middle_initial} {doctor_last_name}<br>
    - Hospital/Clinic: {hospital_name}<br>
    - Doctor Address: {doctor_address}, {doctor_city}, {doctor_state}, {doctor_zip}<br>
    - Admission Date: {admission_date}, Source: {referral_source}, Method: {admission_method}<br>
    - Discharge Date: {discharge_date}, Reason: {discharge_reason}<br>
    - Date of Death: {date_of_death}<br>
    - Diagnosis: {diagnosis}<br>
    - Procedures: {procedures}<br>
    - Medications: {medications}<br>
    - Prepared By: {preparer_name}, {preparer_job_title}
    </div>
    """

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/auth', methods=['GET', 'POST'])
def auth():
    auth_url = CALLBACK_MANAGER.get_auth_url()
    if request.method == 'POST':
        redirected_url = request.form.get('redirected_url')
        if redirected_url:
            auth_code, error = CALLBACK_MANAGER.handle_callback(redirected_url)
            result = CALLBACK_MANAGER.set_auth_code(auth_code) if auth_code else f"<span style='color:#FF4500;'>{error}</span>"
            return render_template('auth.html', auth_url=auth_url, auth_result=result)
        auth_code = request.form.get('auth_code')
        if auth_code:
            result = CALLBACK_MANAGER.set_auth_code(auth_code)
            return render_template('auth.html', auth_url=auth_url, auth_result=result)
    return render_template('auth.html', auth_url=auth_url)

@app.route('/auth/callback', methods=['GET'])
def auth_callback():
    redirected_url = request.url
    result = CALLBACK_MANAGER.handle_callback(redirected_url)
    if "Authentication successful" in result:
        return redirect(url_for('dashboard'))
    return render_template('auth.html', auth_url=CALLBACK_MANAGER.get_auth_url(), auth_result=result)

@app.route('/dashboard', methods=['GET'])
def dashboard():
    if not CALLBACK_MANAGER.access_token:
        return render_template('auth.html', auth_url=CALLBACK_MANAGER.get_auth_url(), auth_result="<span style='color:#FF8C00;'>Please authenticate first.</span>")
    
    data = CALLBACK_MANAGER.get_patient_data()
    if data.startswith('<span'):
        return render_template('dashboard.html', error=data)
    patients_data = json.loads(data)
    patients = [entry['resource'] for entry in patients_data.get('entry', []) if entry['resource'].get('resourceType') == 'Patient']
    return render_template('dashboard.html', patients=patients, authenticated=True)

@app.route('/auth/patient-data', methods=['GET'])
def patient_data():
    data = CALLBACK_MANAGER.get_patient_data()
    return jsonify(json.loads(data) if data and not data.startswith('<span') else {"error": data})

@app.route('/auth/pdf', methods=['GET'])
def generate_meldrx_pdf():
    patient_data = CALLBACK_MANAGER.get_patient_data()
    pdf_path = generate_pdf_from_meldrx(patient_data)
    return send_file(pdf_path, as_attachment=True, download_name="meldrx_patient_data.pdf")

# @app.route('/dashboard', methods=['GET'])
# def dashboard():
#     data = CALLBACK_MANAGER.get_patient_data()
#     if data.startswith('<span'):  # Indicates an error or unauthenticated state
#         return render_template('dashboard.html', error=data)
#     patients_data = json.loads(data)
#     patients = [entry['resource'] for entry in patients_data.get('entry', []) if entry['resource'].get('resourceType') == 'Patient']
#     return render_template('dashboard.html', patients=patients, authenticated=True)

@app.route('/form', methods=['GET', 'POST'])
def discharge_form():
    if request.method == 'POST':
        form_data = request.form.to_dict()
        if 'display' in request.form:
            html_form = display_form(**form_data)
            return render_template('form.html', form_output=html_form)
        elif 'generate_pdf' in request.form:
            pdf_path = generate_pdf_from_form(**form_data)
            return send_file(pdf_path, as_attachment=True, download_name="discharge_form.pdf")
    return render_template('form.html')

@app.route('/analysis', methods=['GET', 'POST'])
def file_analysis():
    if request.method == 'POST':
        file = request.files.get('file')
        file_type = request.form.get('file_type')
        if file:
            file_path = os.path.join('/tmp', file.filename)
            file.save(file_path)
            if file_type == 'dicom':
                result = analyze_dicom_file_with_ai(file_path)
            elif file_type == 'hl7':
                result = analyze_hl7_file_with_ai(file_path)
            elif file_type == 'xml' or file_type == 'ccda' or file_type == 'ccd':
                result = analyze_cda_xml_file_with_ai(file_path)
            elif file_type == 'pdf':
                result = analyze_pdf_file_with_ai(file_path)
            elif file_type == 'csv':
                result = analyze_csv_file_with_ai(file_path)
            else:
                result = "Unsupported file type"
            os.remove(file_path)
            return render_template('analysis.html', result=result, file_type=file_type)
    return render_template('analysis.html')

@app.route('/oneclick', methods=['GET', 'POST'])
def one_click():
    if request.method == 'POST':
        patient_id = request.form.get('patient_id', '')
        first_name = request.form.get('first_name', '')
        last_name = request.form.get('last_name', '')
        pdf_path, status = generate_discharge_paper_one_click(CALLBACK_MANAGER.api, patient_id, first_name, last_name)
        if pdf_path:
            return send_file(pdf_path, as_attachment=True, download_name="discharge_summary.pdf")
        return render_template('oneclick.html', status=status)
    return render_template('oneclick.html')

if __name__ == '__main__':
    port = int(os.getenv("PORT", 7860))  # Default to 5000, override with PORT env var
    app.run(debug=False, host='0.0.0.0', port=port)