File size: 7,972 Bytes
5372c12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import gradio as gr
from meldrx import MeldRxAPI  
import json

# CallbackManager class to handle OAuth callbacks
class CallbackManager:
    def __init__(self, client_id: str, redirect_uri: str, workspace_id: str, client_secret: str = None):
        """
        Initialize the CallbackManager with MeldRx API credentials.

        Args:
            client_id (str): The client ID from MeldRx Developer Portal.
            redirect_uri (str): The redirect URI for the Gradio app (e.g., Space URL + /callback).
            workspace_id (str): The workspace slug/ID.
            client_secret (str, optional): The client secret (for confidential clients).
        """
        self.api = MeldRxAPI(client_id, redirect_uri, workspace_id, client_secret)
        self.auth_code = None
        self.access_token = None

    def get_auth_url(self) -> str:
        """Generate and return the SMART on FHIR authorization URL."""
        return self.api.get_authorization_url()

    def set_auth_code(self, code: str) -> str:
        """Set the authorization code and attempt to get an access token."""
        self.auth_code = code
        if self.api.authenticate_with_code(code):
            self.access_token = self.api.access_token
            return f"Authentication successful! Access Token: {self.access_token[:10]}... (truncated)"
        return "Authentication failed. Please check the code."

    def get_patient_data(self) -> str:
        """Retrieve patient data using the access token."""
        if not self.access_token:
            return "Not authenticated. Please provide a valid authorization code first."
        patients = self.api.get_patients()
        if patients is not None:
            return json.dumps(patients, indent=2) if patients else "No patient data returned."
        return "Failed to retrieve patient data."

# Discharge form display function
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
):
    form = f"""
    **Patient Discharge Form**
    
    **Patient Details:**
    - Name: {first_name} {middle_initial} {last_name}
    - Date of Birth: {dob}, Age: {age}, Sex: {sex}
    - Address: {address}, {city}, {state}, {zip_code}
    
    **Primary Healthcare Professional Details:**
    - Name: {doctor_first_name} {doctor_middle_initial} {doctor_last_name}
    - Hospital/Clinic: {hospital_name}
    - Address: {doctor_address}, {doctor_city}, {doctor_state}, {doctor_zip}
    
    **Admission and Discharge Details:**
    - Date of Admission: {admission_date}
    - Source of Referral: {referral_source}
    - Method of Admission: {admission_method}
    - Date of Discharge: {discharge_date}
    - Discharge Reason: {discharge_reason}
    - Date of Death (if applicable): {date_of_death}
    
    **Diagnosis & Procedures:**
    - Diagnosis: {diagnosis}
    - Procedures: {procedures}
    
    **Medication Details:**
    - Medications on Discharge: {medications}
    
    **Prepared By:**
    - Name: {preparer_name}, Job Title: {preparer_job_title}
    """
    return form

# Initialize CallbackManager with your credentials
CALLBACK_MANAGER = CallbackManager(
    client_id="your_client_id",  # Replace with actual client ID
    redirect_uri="https://multitransformer-discharge-guard.hf.space/callback",
    workspace_id="your_workspace_id",  # Replace with actual workspace ID
    client_secret=None  # Replace with actual secret if using a confidential client
)

# Gradio interface
with gr.Blocks() as demo:
    gr.Markdown("# Patient Discharge Form with MeldRx Integration")

    # Authentication Section
    with gr.Tab("Authenticate with MeldRx"):
        gr.Markdown("## SMART on FHIR Authentication")
        auth_url_output = gr.Textbox(label="Authorization URL", value=CALLBACK_MANAGER.get_auth_url(), interactive=False)
        gr.Markdown("Copy the URL above, open it in a browser, log in, and paste the 'code' from the redirect URL below.")
        auth_code_input = gr.Textbox(label="Authorization Code")
        auth_submit = gr.Button("Submit Code")
        auth_result = gr.Textbox(label="Authentication Result")
        patient_data_button = gr.Button("Fetch Patient Data")
        patient_data_output = gr.Textbox(label="Patient Data")

        auth_submit.click(
            fn=CALLBACK_MANAGER.set_auth_code,
            inputs=auth_code_input,
            outputs=auth_result
        )
        patient_data_button.click(
            fn=CALLBACK_MANAGER.get_patient_data,
            inputs=None,
            outputs=patient_data_output
        )

    # Discharge Form Section
    with gr.Tab("Discharge Form"):
        gr.Markdown("## Patient Details")
        with gr.Row():
            first_name = gr.Textbox(label="First Name")
            last_name = gr.Textbox(label="Last Name")
            middle_initial = gr.Textbox(label="Middle Initial")
        
        with gr.Row():
            dob = gr.Textbox(label="Date of Birth")
            age = gr.Textbox(label="Age")
            sex = gr.Textbox(label="Sex")
        
        address = gr.Textbox(label="Address")
        with gr.Row():
            city = gr.Textbox(label="City")
            state = gr.Textbox(label="State")
            zip_code = gr.Textbox(label="Zip Code")
        
        gr.Markdown("## Primary Healthcare Professional Details")
        with gr.Row():
            doctor_first_name = gr.Textbox(label="Doctor's First Name")
            doctor_last_name = gr.Textbox(label="Doctor's Last Name")
            doctor_middle_initial = gr.Textbox(label="Middle Initial")
        
        hospital_name = gr.Textbox(label="Hospital/Clinic Name")
        doctor_address = gr.Textbox(label="Address")
        with gr.Row():
            doctor_city = gr.Textbox(label="City")
            doctor_state = gr.Textbox(label="State")
            doctor_zip = gr.Textbox(label="Zip Code")
        
        gr.Markdown("## Admission and Discharge Details")
        with gr.Row():
            admission_date = gr.Textbox(label="Date of Admission")
            referral_source = gr.Textbox(label="Source of Referral")
        
        admission_method = gr.Textbox(label="Method of Admission")
        with gr.Row():
            discharge_date = gr.Textbox(label="Date of Discharge")
            discharge_reason = gr.Radio(["Treated", "Transferred", "Discharge Against Advice", "Patient Died"], label="Discharge Reason")
        
        date_of_death = gr.Textbox(label="Date of Death (if applicable)")
        
        gr.Markdown("## Diagnosis & Procedures")
        diagnosis = gr.Textbox(label="Diagnosis")
        procedures = gr.Textbox(label="Operation & Procedures")
        
        gr.Markdown("## Medication Details")
        medications = gr.Textbox(label="Medication on Discharge")
        
        gr.Markdown("## Prepared By")
        with gr.Row():
            preparer_name = gr.Textbox(label="Name")
            preparer_job_title = gr.Textbox(label="Job Title")
        
        submit = gr.Button("Generate Form")
        output = gr.Markdown()
        
        submit.click(
            display_form,
            inputs=[
                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
            ],
            outputs=output
        )

demo.launch()