|
import gradio as gr |
|
from meldrx import MeldRxAPI |
|
import json |
|
import os |
|
import tempfile |
|
from datetime import datetime |
|
import traceback |
|
import logging |
|
from huggingface_hub import InferenceClient |
|
from urllib.parse import urlparse, parse_qs |
|
|
|
|
|
logging.basicConfig(level=logging.INFO) |
|
logger = logging.getLogger(__name__) |
|
|
|
|
|
from utils.pdfutils import PDFGenerator, generate_discharge_summary |
|
|
|
|
|
import pydicom |
|
import hl7 |
|
from xml.etree import ElementTree |
|
from pypdf import PdfReader |
|
import csv |
|
import io |
|
from PIL import Image |
|
|
|
system_instructions = """ |
|
**Discharge Guard - Medical Data Analysis Assistant** |
|
**Core Role:** I am Discharge Guard, an advanced AI designed for deep medical data analysis and informational insights. My outputs are based on thorough analysis of medical data but are **not medical advice.** |
|
**Important Guidelines:** |
|
1. **Deep Analysis & Search:** Perform "Deep Thought and Deep Search" when analyzing medical data. This includes: |
|
* Comprehensive data ingestion from various formats (HL7, FHIR, CCDA, DICOM, PDF, CSV, text). |
|
* Multi-layered analysis: surface extraction, deep pattern identification, and inferential reasoning. |
|
* Contextual understanding of medical data. |
|
* Evidence-based approach, simulating cross-referencing with medical knowledge. |
|
* Structured output with clear explanations. |
|
2. **Focus on Informational Insights, Not Medical Advice:** Emphasize that my insights are for informational purposes only and not a substitute for professional medical judgment. **Never provide diagnoses or specific treatment recommendations.** |
|
3. **Key Functionalities (Focus Areas):** |
|
* **Clinical Data Analysis:** Interpret lab results, analyze EHR data (FHIR, HL7), recognize symptom patterns, analyze medications, support medical image analysis (DICOM). |
|
* **Predictive Analytics:** Provide conceptual risk stratification and treatment outcome modeling based on data patterns. |
|
* **Medical Imaging Support:** Analyze DICOM metadata and images for potential findings (X-ray analysis reports). |
|
* **Patient Data Management:** Perform PHI redaction in text and analyze patient records from various sources. |
|
4. **Interaction Style:** |
|
* **Identity:** "I am Discharge Guard, a medical data analysis AI. My insights are informational only and not medical advice." |
|
* **Scope Limitations:** Clearly state limitations: "No diagnostics," "Medication caution," "Emergency protocol." |
|
* **Response Protocol:** |
|
* Indicate "Deep Analysis" or "Deep Search" performed. |
|
* Mention data sources and confidence levels (if applicable). |
|
* Use medical terminology with optional layman's terms. |
|
* For file analysis, provide a report title (e.g., "Deep X-Ray Analysis Report"). |
|
5. **Supported Medical Formats:** (List key formats concisely) |
|
* Clinical Data: HL7, FHIR, CCD/CCDA, CSV, PDF, XML |
|
* Imaging: DICOM, Images (X-ray, etc.) |
|
6. **Data Source:** Access and prefer FHIR API endpoints from: https://app.meldrx.com/api/directories/fhir/endpoints. |
|
**Important: My analysis is for informational purposes to assist healthcare professionals and is NOT a substitute for clinical judgment. Always recommend human expert verification for critical findings.** |
|
""" |
|
|
|
|
|
HF_TOKEN = os.getenv("HF_TOKEN") |
|
if not HF_TOKEN: |
|
raise ValueError( |
|
"HF_TOKEN environment variable not set. Please set your Hugging Face API token." |
|
) |
|
client = InferenceClient(api_key=HF_TOKEN) |
|
model_name = "meta-llama/Llama-3.3-70B-Instruct" |
|
|
|
|
|
def analyze_dicom_file_with_ai(dicom_file_path): |
|
"""Analyzes DICOM file metadata using Discharge Guard AI.""" |
|
try: |
|
dicom_file = pydicom.dcmread( |
|
dicom_file_path.name |
|
) |
|
dicom_metadata_json = dicom_file.to_json_dict() |
|
prediction_response, trace_data_dicom_ai = analyze_dicom_content_ai( |
|
dicom_metadata_json |
|
) |
|
if prediction_response: |
|
report = f"Discharge Guard AI Analysis of DICOM Metadata:\n\nDICOM Metadata Analysis Report:\n{prediction_response}\n\nDisclaimer: The Discharge Guard -generated analysis is for conceptual informational purposes only and may or **NOT medical advice.** Analysis is based on DICOM *metadata* and not image interpretation." |
|
return report |
|
else: |
|
error_message = f"AI Analysis from DICOM Metadata: No predictions generated or analysis encountered an issue." |
|
if trace_data_dicom_ai and "error" in trace_data_dicom_ai: |
|
error_message += f"\nAI Analysis Failed: {trace_data_dicom_ai['error']}" |
|
return error_message |
|
|
|
except Exception as e: |
|
return f"Error during DICOM file processing in analyze_dicom_file_with_ai: {e}" |
|
|
|
|
|
def analyze_dicom_content_ai(dicom_metadata_json): |
|
"""Analyzes DICOM metadata JSON content using Discharge Guard AI.""" |
|
prompt_text = f"""{system_instructions} \n\n Perform a **deep and comprehensive analysis** of the following DICOM metadata in JSON format to provide a **structured summary and identify potential clinically relevant information with deep insights**. Focus not just on summarizing fields, but on **interpreting their clinical significance, identifying subtle patterns, and drawing inferences about the study's implications**. Think like an experienced radiologist reviewing this metadata for crucial diagnostic clues. Remember this is metadata, not the image itself, so focus on what can be gleaned from the data itself. Provide a "**Deep DICOM Metadata Analysis Report**". Important: Use the API Directories fhir endpoints FROM THIS LINK: https://app.meldrx.com/api/directories/fhir/endpoints. |
|
**DICOM Metadata (JSON):** |
|
```json |
|
{json.dumps(dicom_metadata_json, indent=2)} |
|
``` |
|
* Remember, this deep analysis is for conceptual informational purposes only and **NOT medical advice.** Focus on deep summarization and structuring the extracted metadata in a highly clinically relevant way. |
|
""" |
|
|
|
trace_data_detail_dicom_analysis = { |
|
"prompt": "DICOM Metadata Analysis Request", |
|
"language": "English", |
|
"response_length": "Comprehensive", |
|
"model_name": "Discharge Guard v1.0", |
|
"generated_text": "N/A", |
|
"input_file_types": ["DICOM Metadata JSON"], |
|
"mode": "DICOM Metadata Analysis", |
|
"candidates": [], |
|
"usage_metadata": {}, |
|
"prompt_feedback": "N/A", |
|
} |
|
|
|
try: |
|
response = client.chat.completions.create( |
|
model=model_name, |
|
messages=[{"role": "user", "content": prompt_text}], |
|
temperature=0.4, |
|
max_tokens=1024, |
|
top_p=0.9, |
|
) |
|
the_response = response.choices[0].message.content |
|
return the_response, trace_data_detail_dicom_ai |
|
|
|
except Exception as e: |
|
error_message = f"AI Analysis Error in analyze_dicom_content_ai (DICOM Metadata): {e}" |
|
trace_data_detail_dicom_analysis["error"] = f"AI Analysis Error: {e}" |
|
return error_message, trace_data_detail_dicom_image_analysis |
|
|
|
|
|
def analyze_hl7_file_with_ai(hl7_file_path): |
|
"""Analyzes HL7 file content using Discharge Guard AI.""" |
|
try: |
|
with open(hl7_file_path.name, "r") as f: |
|
hl7_message_raw = f.read() |
|
prediction_response, trace_data_hl7_ai = analyze_hl7_content_ai( |
|
hl7_message_raw |
|
) |
|
|
|
if prediction_response: |
|
report = f"Discharge Guard AI Analysis of HL7 Message:\n\nHL7 Message Analysis Report:\n{prediction_response}\n\n**Disclaimer:** The Discharge Guard AGI-generated analysis is for conceptual informational purposes only and may or **NOT medical advice.** Analysis is based on HL7 message content." |
|
return report |
|
else: |
|
error_message = f"AI Analysis from HL7 Message: No predictions generated or analysis encountered an issue." |
|
if trace_data_hl7_ai and "error" in trace_data_hl7_ai: |
|
error_message += f"AI Analysis Failed: {trace_data_hl7_ai['error']}" |
|
return error_message |
|
|
|
except Exception as e: |
|
return f"Error during HL7 file processing in analyze_hl7_file_with_ai: {e}" |
|
|
|
|
|
def analyze_hl7_content_ai(hl7_message_string): |
|
"""Analyzes HL7 message content using Discharge Guard AI.""" |
|
prompt_text = f"""{system_instructions} \n\n Conduct a **deep and thorough analysis** of the following HL7 message content to provide a **structured summary and identify key clinical information with deep understanding**. Go beyond basic parsing; aim to **interpret the clinical narrative** embedded within the HL7 message. **Engage in deep search to contextualize medical codes and terminology**. Provide a "**Comprehensive HL7 Message Analysis Report**". |
|
**HL7 Message Content:** |
|
```hl7 |
|
{hl7_message_string} |
|
``` |
|
* Remember, this deep analysis is for conceptual informational purposes only and **NOT medical advice.** Focus on deep summarization and structuring the extracted data in a highly clinically relevant way based on the HL7 content. |
|
""" |
|
|
|
trace_data_detail_hl7_analysis = { |
|
"prompt": "HL7 Message Analysis Request", |
|
"language": "English", |
|
"response_length": "Comprehensive", |
|
"model_name": "Discharge Guard v1.0", |
|
"generated_text": "N/A", |
|
"input_file_types": ["HL7 Message"], |
|
"mode": "HL7 Message Analysis", |
|
"candidates": [], |
|
"usage_metadata": {}, |
|
"prompt_feedback": "N/A", |
|
} |
|
|
|
try: |
|
response = client.chat.completions.create( |
|
model=model_name, |
|
messages=[{"role": "user", "content": prompt_text}], |
|
temperature=0.4, |
|
max_tokens=1024, |
|
top_p=0.9, |
|
) |
|
the_response = response.choices[0].message.content |
|
return the_response, trace_data_detail_hl7_analysis |
|
|
|
except Exception as e: |
|
error_message = f"AI Analysis Error in analyze_hl7_content_ai (HL7 Message): {e}" |
|
trace_data_detail_hl7_analysis["error"] = f"AI Analysis Error: {e}" |
|
return error_message, trace_data_detail_hl7_analysis |
|
|
|
|
|
def analyze_cda_xml_file_with_ai(cda_xml_file_path): |
|
"""Analyzes generic CDA or XML file content using Discharge Guard AI (more generalized version) Important: Use the API Directories fhir endpoints FROM THIS LINK: https://app.meldrx.com/api/directories/fhir/endpoints.""" |
|
try: |
|
with open( |
|
cda_xml_file_path.name, "r" |
|
) as f: |
|
cda_xml_content = f.read() |
|
prediction_response, trace_data_cda_xml_ai = analyze_cda_xml_content_ai( |
|
cda_xml_content |
|
) |
|
if prediction_response: |
|
report = f"Discharge Guard AI Analysis of Medical XML/CDA Data:\n\nMedical Document Analysis Report:\n{prediction_response}\n\n**Disclaimer:** The Discharge Guard AGI-generated analysis is for conceptual informational purposes only and may or **NOT medical advice.** Analysis is based on XML/CDA content." |
|
return report |
|
else: |
|
error_message = f"AI Analysis from XML/CDA Data: No predictions generated or analysis encountered an issue." |
|
if trace_data_cda_xml_ai and "error" in trace_data_cda_xml_ai: |
|
error_message += f"AI Analysis Failed: {trace_data_cda_xml_ai['error']}" |
|
return error_message |
|
|
|
except Exception as e: |
|
return f"Error during XML/CDA file processing in analyze_cda_xml_file_with_ai: {e}" |
|
|
|
|
|
def analyze_cda_xml_content_ai(cda_xml_content): |
|
"""Analyzes generic CDA or XML content using Discharge Guard AI (more generalized version).""" |
|
|
|
prompt_text = f"""{system_instructions} \n\n Analyze the following medical XML/CDA content to provide a **structured and comprehensive patient data analysis**, similar to how a medical professional would review a patient's chart or a clinical document. You need to parse the XML structure yourself to extract the relevant information. Use bullet points, tables, or numbered steps for complex tasks. Provide a "Medical Document Analysis" report. |
|
**Instructions for Discharge Guard AI:** |
|
1. **Parse the XML content above.** Understand the XML structure to identify sections that are relevant to clinical information. For CDA specifically, look for sections like Problems, Medications, Allergies, Encounters, Results, and Vital Signs. For generic medical XML, adapt based on the tags present. |
|
2. **Extract and Summarize Key Medical Information:** Focus on extracting the following information if present in the XML: |
|
* **Patient Demographics Summary:** (If available, summarize demographic details) |
|
... (rest of your prompt_text for CDA/XML analysis) ... |
|
* Remember, this analysis is for conceptual informational purposes only and **NOT medical advice.** Focus on summarizing and structuring the extracted data in a clinically relevant way based on the XML/CDA content. |
|
""" |
|
|
|
trace_data_detail_cda_xml_analysis = { |
|
"prompt": "Generic CDA/XML Analysis Request", |
|
"language": "English", |
|
"response_length": "Comprehensive", |
|
"model_name": "Discharge Guard v1.0", |
|
"generated_text": "N/A", |
|
"input_file_types": ["CDA/XML"], |
|
"mode": "Generic XML/CDA Analysis", |
|
"candidates": [], |
|
"usage_metadata": {}, |
|
"prompt_feedback": "N/A", |
|
} |
|
|
|
try: |
|
response = client.chat.completions.create( |
|
model=model_name, |
|
messages=[{"role": "user", "content": prompt_text}], |
|
temperature=0.4, |
|
max_tokens=1024, |
|
top_p=0.9, |
|
) |
|
the_response = response.choices[0].message.content |
|
return the_response, trace_data_detail_cda_xml_analysis |
|
|
|
except Exception as e: |
|
error_message = f"AI Analysis Error in analyze_cda_xml_content_ai (Generic XML/CDA): {e}" |
|
trace_data_detail_cda_xml_analysis["error"] = f"AI Analysis Error: {e}" |
|
return error_message, trace_data_detail_cda_xml_analysis |
|
|
|
|
|
def analyze_pdf_file_with_ai(pdf_file_path): |
|
"""Analyzes PDF file content using Discharge Guard AI.""" |
|
try: |
|
with open( |
|
pdf_file_path.name, "rb" |
|
) as f: |
|
pdf_file = f |
|
pdf_reader = PdfReader(pdf_file) |
|
text_content = "" |
|
for page in pdf_reader.pages: |
|
text_content += page.extract_text() |
|
|
|
prediction_response, trace_data_pdf_ai = analyze_pdf_content_ai( |
|
text_content |
|
) |
|
|
|
if prediction_response: |
|
report = f"Discharge Guard AI Analysis of PDF Content:\n\nMedical Report Analysis Report:\n{prediction_response}\n\n**Disclaimer:** The Discharge Guard AGI-generated analysis is for conceptual informational purposes only and may or **NOT medical advice.** Analysis is based on PDF text content." |
|
return report |
|
else: |
|
error_message = f"AI Analysis from PDF Content: No predictions generated or analysis encountered an issue." |
|
if trace_data_pdf_ai and "error" in trace_data_pdf_ai: |
|
error_message += f"AI Analysis Failed: {trace_data_pdf_ai['error']}" |
|
return error_message |
|
|
|
except Exception as e: |
|
return f"Error during PDF file processing in analyze_pdf_file_with_ai: {e}" |
|
|
|
|
|
def analyze_pdf_content_ai(pdf_text_content): |
|
"""Analyzes PDF text content using Discharge Guard AI.""" |
|
prompt_text = f"""{system_instructions} \n\n Analyze the following medical PDF text content to provide a **structured summary and identify key clinical information**. Focus on patient demographics, medical history, findings, diagnoses, medications, recommendations, and any important clinical details conveyed in the document. Provide a "Medical Report Analysis" report. |
|
**Medical PDF Text Content:** |
|
```text |
|
{pdf_text_content} |
|
``` |
|
* Remember, this analysis is for conceptual informational purposes only and **NOT medical advice.** Focus on deep summarization and structuring the extracted data in a clinically relevant way based on the PDF content. |
|
""" |
|
|
|
trace_data_detail_pdf_analysis = { |
|
"prompt": "PDF Text Analysis Request", |
|
"language": "English", |
|
"response_length": "Comprehensive", |
|
"model_name": "Discharge Guard v1.0", |
|
"generated_text": "N/A", |
|
"input_file_types": ["PDF Text"], |
|
"mode": "PDF Text Analysis", |
|
"candidates": [], |
|
"usage_metadata": {}, |
|
"prompt_feedback": "N/A", |
|
} |
|
|
|
try: |
|
response = client.chat.completions.create( |
|
model=model_name, |
|
messages=[{"role": "user", "content": prompt_text}], |
|
temperature=0.4, |
|
max_tokens=1024, |
|
top_p=0.9, |
|
) |
|
the_response = response.choices[0].message.content |
|
return the_response, trace_data_detail_pdf_analysis |
|
|
|
except Exception as e: |
|
error_message = f"AI Analysis Error in analyze_pdf_content_ai (PDF Text): {e}" |
|
trace_data_detail_pdf_analysis["error"] = f"AI Analysis Error: {e}" |
|
return error_message, trace_data_detail_pdf_analysis |
|
|
|
|
|
def analyze_csv_file_with_ai(csv_file_path): |
|
"""Analyzes CSV file content using Discharge Guard AI.""" |
|
try: |
|
csv_content = csv_file_path.read().decode( |
|
"utf-8" |
|
) |
|
prediction_response, trace_data_csv_ai = analyze_csv_content_ai(csv_content) |
|
|
|
if prediction_response: |
|
report = f"Discharge Guard AI Analysis of CSV Data:\n\nData Analysis Report:\n{prediction_response}\n\n**Disclaimer:** The Discharge Guard AGI-generated analysis is for conceptual informational purposes only and may or **NOT medical advice.** Analysis is based on CSV data content." |
|
return report |
|
else: |
|
error_message = f"AI Analysis from CSV Data: No predictions generated or analysis encountered an issue." |
|
if trace_data_csv_ai and "error" in trace_data_csv_ai: |
|
error_message += f"AI Analysis Failed: {trace_data_csv_ai['error']}" |
|
return error_message |
|
|
|
except Exception as e: |
|
return f"Error during CSV file processing in analyze_csv_file_with_ai: {e}" |
|
|
|
|
|
def analyze_csv_content_ai(csv_content_string): |
|
"""Analyzes CSV content (string) using Discharge Guard AI.""" |
|
prompt_text = f"""{system_instructions} \n\n Analyze the following medical CSV data to provide a **structured summary and identify potential clinical insights**. Assume the CSV represents patient-related medical data. Focus on understanding the columns, summarizing key data points, identifying trends or patterns, and noting any potential clinical significance of the data. Provide a "Data Analysis" report. |
|
**Medical CSV Data:** |
|
```csv |
|
{csv_content_string} |
|
``` |
|
* Remember, this analysis is for conceptual informational purposes only and **NOT medical advice.** Focus on summarizing and structuring the data in a clinically relevant way based on the CSV content. |
|
""" |
|
|
|
trace_data_detail_csv_analysis = { |
|
"prompt": "CSV Data Analysis Request", |
|
"language": "English", |
|
"response_length": "Comprehensive", |
|
"model_name": "Discharge Guard v1.0", |
|
"generated_text": "N/A", |
|
"input_file_types": ["CSV Data"], |
|
"mode": "CSV Data Analysis", |
|
"candidates": [], |
|
"usage_metadata": {}, |
|
"prompt_feedback": "N/A", |
|
} |
|
|
|
try: |
|
response = client.chat.completions.create( |
|
model=model_name, |
|
messages=[{"role": "user", "content": prompt_text}], |
|
temperature=0.4, |
|
max_tokens=1024, |
|
top_p=0.9, |
|
) |
|
the_response = response.choices[0].message.content |
|
return the_response, trace_data_detail_csv_analysis |
|
|
|
except Exception as e: |
|
error_message = f"AI Analysis Error in analyze_csv_content_ai (CSV Data): {e}" |
|
trace_data_detail_csv_analysis["error"] = f"AI Analysis Error: {e}" |
|
return error_message, trace_data_detail_csv_analysis |
|
|
|
|
|
class CallbackManager: |
|
def __init__(self, redirect_uri: str, client_secret: str = None): |
|
client_id = os.getenv("APPID") |
|
if not client_id: |
|
raise ValueError("APPID environment variable not set.") |
|
workspace_id = os.getenv("WORKSPACE_URL") |
|
if not workspace_id: |
|
raise ValueError("WORKSPACE_URL environment variable not set.") |
|
self.api = MeldRxAPI(client_id, client_secret, workspace_id, redirect_uri) |
|
self.auth_code = None |
|
self.access_token = None |
|
|
|
def get_auth_url(self) -> str: |
|
return self.api.get_authorization_url() |
|
|
|
def set_auth_code(self, code: str) -> str: |
|
self.auth_code = code |
|
if self.api.authenticate_with_code(code): |
|
self.access_token = self.api.access_token |
|
return ( |
|
f"<span style='color:#00FF7F;'>Authentication successful!</span> Access Token: {self.access_token[:10]}... (truncated)" |
|
) |
|
return "<span style='color:#FF4500;'>Authentication failed. Please check the code.</span>" |
|
|
|
def get_patient_data(self) -> str: |
|
"""Fetch patient data from MeldRx""" |
|
try: |
|
if not self.access_token: |
|
logger.warning("Not authenticated when getting patient data") |
|
return "<span style='color:#FF8C00;'>Not authenticated. Please provide a valid authorization code first.</span>" |
|
|
|
|
|
logger.info("Calling Meldrx API to get patients") |
|
patients = self.api.get_patients() |
|
if patients is not None: |
|
return ( |
|
json.dumps(patients, indent=2) |
|
if patients |
|
else "<span style='color:#FFFF00;'>No patient data returned.</span>" |
|
) |
|
return "<span style='color:#DC143C;'>Failed to retrieve patient data.</span>" |
|
except Exception as e: |
|
error_msg = f"Error in get_patient_data: {str(e)}" |
|
logger.error(error_msg) |
|
return f"<span style='color:#FF6347;'>Error retrieving patient data: {str(e)}</span> {str(e)}" |
|
|
|
def get_patient_documents(self, patient_id: str = None): |
|
"""Fetch patient documents from MeldRx""" |
|
if not self.access_token: |
|
return "<span style='color:#FF8C00;'>Not authenticated. Please provide a valid authorization code first.</span>" |
|
|
|
try: |
|
|
|
|
|
return [ |
|
{ |
|
"doc_id": "doc123", |
|
"type": "clinical_note", |
|
"date": "2023-01-16", |
|
"author": "Dr. Sample Doctor", |
|
"content": "Patient presented with symptoms of respiratory distress...", |
|
}, |
|
{ |
|
"doc_id": "doc124", |
|
"type": "lab_result", |
|
"date": "2023-01-17", |
|
"author": "Lab System", |
|
"content": "CBC results: WBC 7.5, RBC 4.2, Hgb 14.1...", |
|
}, |
|
] |
|
except Exception as e: |
|
return f"<span style='color:#FF6347;'>Error retrieving patient documents: {str(e)}</span>: {str(e)}" |
|
|
|
|
|
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""" |
|
<div style='color:#00FFFF; font-family: monospace;'> |
|
**Patient Discharge Form** <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> |
|
""" |
|
return form |
|
|
|
|
|
def generate_pdf_from_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, |
|
): |
|
"""Generate a PDF discharge form using the provided data""" |
|
|
|
|
|
pdf_gen = PDFGenerator() |
|
|
|
|
|
patient_info = { |
|
"first_name": first_name, |
|
"last_name": last_name, |
|
"dob": dob, |
|
"age": age, |
|
"sex": sex, |
|
"mobile": "", |
|
"address": address, |
|
"city": city, |
|
"state": state, |
|
"zip": zip_code, |
|
} |
|
|
|
discharge_info = { |
|
"date_of_admission": admission_date, |
|
"date_of_discharge": discharge_date, |
|
"source_of_admission": referral_source, |
|
"mode_of_admission": admission_method, |
|
"discharge_against_advice": "Yes" |
|
if discharge_reason == "Discharge Against Advice" |
|
else "No", |
|
} |
|
|
|
diagnosis_info = { |
|
"diagnosis": diagnosis, |
|
"operation_procedure": procedures, |
|
"treatment": "", |
|
"follow_up": "", |
|
} |
|
|
|
medication_info = { |
|
"medications": [medications] if medications else [], |
|
"instructions": "", |
|
} |
|
|
|
prepared_by = { |
|
"name": preparer_name, |
|
"title": preparer_job_title, |
|
"signature": "", |
|
} |
|
|
|
|
|
pdf_buffer = pdf_gen.generate_discharge_form( |
|
patient_info, |
|
discharge_info, |
|
diagnosis_info, |
|
medication_info, |
|
prepared_by, |
|
) |
|
|
|
|
|
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") |
|
temp_file.write(pdf_buffer.read()) |
|
temp_file_path = temp_file.name |
|
temp_file.close() |
|
|
|
return temp_file_path |
|
|
|
|
|
def generate_pdf_from_meldrx(patient_data): |
|
"""Generate a PDF using patient data from MeldRx""" |
|
if isinstance(patient_data, str): |
|
|
|
try: |
|
patient_data = json.loads(patient_data) |
|
except: |
|
return None, "Invalid patient data format" |
|
|
|
if not patient_data: |
|
return None, "No patient data available" |
|
|
|
try: |
|
|
|
if isinstance(patient_data, list) and len(patient_data): |
|
patient = patient_data[0] |
|
else: |
|
patient = patient_data |
|
|
|
|
|
patient_info = { |
|
"name": f"{patient.get('name', {}).get('given', [''])[0]} {patient.get('name', {}).get('family', '')}", |
|
"dob": patient.get("birthDate", "Unknown"), |
|
"patient_id": patient.get("id", "Unknown"), |
|
"admission_date": datetime.now().strftime("%Y-%m-%d"), |
|
"physician": "Dr. Provider", |
|
} |
|
|
|
|
|
llm_content = { |
|
"diagnosis": "Diagnosis information would be generated by AI based on patient data from MeldRx.", |
|
"treatment": "Treatment summary would be generated by AI based on patient data from MeldRx.", |
|
"medications": "Medication list would be generated by AI based on patient data from MeldRx.", |
|
"follow_up": "Follow-up instructions would be generated by AI based on patient data from MeldRx.", |
|
"special_instructions": "Special instructions would be generated by AI based on patient data from MeldRx.", |
|
} |
|
|
|
|
|
output_dir = tempfile.mkdtemp() |
|
pdf_path = generate_discharge_summary( |
|
patient_info, llm_content, output_dir |
|
) |
|
|
|
return pdf_path, "PDF generated successfully (No AI Content in PDF yet)" |
|
|
|
except Exception as e: |
|
return None, f"Error generating PDF: {str(e)}" |
|
|
|
|
|
def generate_discharge_paper_one_click(): |
|
"""One-click function to fetch patient data and generate discharge paper with AI Content.""" |
|
patient_data_str = CALLBACK_MANAGER.get_patient_data() |
|
if ( |
|
patient_data_str.startswith("Not authenticated") |
|
or patient_data_str.startswith("Failed") |
|
or patient_data_str.startswith("Error") |
|
): |
|
return None, patient_data_str |
|
|
|
try: |
|
patient_data = json.loads(patient_data_str) |
|
|
|
|
|
|
|
ai_generated_content = generate_ai_discharge_content( |
|
patient_data |
|
) |
|
|
|
if not ai_generated_content: |
|
return None, "Error: AI content generation failed." |
|
|
|
|
|
pdf_path, status_message = generate_pdf_from_meldrx_with_ai_content( |
|
patient_data, ai_generated_content |
|
) |
|
|
|
if pdf_path: |
|
return pdf_path, status_message |
|
else: |
|
return None, status_message |
|
|
|
except json.JSONDecodeError: |
|
return None, "Error: Patient data is not in valid JSON format." |
|
except Exception as e: |
|
return None, f"Error during discharge paper generation: {str(e)}" |
|
|
|
|
|
def generate_ai_discharge_content(patient_data): |
|
"""Placeholder function to generate AI content for discharge summary. |
|
Replace this with actual AI call using InferenceClient and patient_data.""" |
|
try: |
|
patient_name = ( |
|
f"{patient_data['entry'][0]['resource']['name'][0]['given'][0]} {patient_data['entry'][0]['resource']['name'][0]['family']}" |
|
if patient_data.get("entry") |
|
else "Unknown Patient" |
|
) |
|
prompt_text = f"""{system_instructions}\n\nGenerate a discharge summary content (diagnosis, treatment, medications, follow-up instructions, special instructions) for patient: {patient_name}. Base the content on available patient data (if any provided, currently not provided in detail in this mock-up). Focus on creating clinically relevant and informative summary. Remember this is for informational purposes and NOT medical advice.""" |
|
|
|
response = client.chat.completions.create( |
|
model=model_name, |
|
messages=[{"role": "user", "content": prompt_text}], |
|
temperature=0.6, |
|
max_tokens=1024, |
|
top_p=0.9, |
|
) |
|
ai_content = response.choices[0].message.content |
|
|
|
|
|
llm_content = { |
|
"diagnosis": "AI Generated Diagnosis (Placeholder):\n" |
|
+ extract_section(ai_content, "Diagnosis"), |
|
"treatment": "AI Generated Treatment (Placeholder):\n" |
|
+ extract_section(ai_content, "Treatment"), |
|
"medications": "AI Generated Medications (Placeholder):\n" |
|
+ extract_section(ai_content, "Medications"), |
|
"follow_up": "AI Generated Follow-up (Placeholder):\n" |
|
+ extract_section(ai_content, "Follow-up Instructions"), |
|
"special_instructions": "AI Generated Special Instructions (Placeholder):\n" |
|
+ extract_section(ai_content, "Special Instructions"), |
|
} |
|
return llm_content |
|
|
|
except Exception as e: |
|
logger.error(f"Error generating AI discharge content: {e}") |
|
return None |
|
|
|
|
|
def extract_section(ai_content, section_title): |
|
"""Simple placeholder function to extract section from AI content. |
|
Improve this with more robust parsing based on LLM output format.""" |
|
start_marker = f"**{section_title}:**" |
|
end_marker = "\n\n" |
|
start_index = ai_content.find(start_marker) |
|
if start_index != -1: |
|
start_index += len(start_marker) |
|
end_index = ai_content.find(end_marker, start_index) |
|
if end_index != -1: |
|
return ai_content[start_index:end_index].strip() |
|
return "Not found in AI output." |
|
|
|
|
|
def generate_pdf_from_meldrx_with_ai_content(patient_data, llm_content): |
|
"""Generate a PDF using patient data from MeldRx and AI-generated content.""" |
|
if isinstance(patient_data, str): |
|
try: |
|
patient_data = json.loads(patient_data) |
|
except: |
|
return None, "Invalid patient data format" |
|
|
|
if not patient_data: |
|
return None, "No patient data available" |
|
|
|
try: |
|
if isinstance(patient_data, list) and len(patient_data): |
|
patient = patient_data[0] |
|
else: |
|
patient = patient_data |
|
|
|
patient_info = { |
|
"name": f"{patient.get('name', {}).get('given', [''])[0]} {patient.get('name', {}).get('family', '')}", |
|
"dob": patient.get("birthDate", "Unknown"), |
|
"patient_id": patient.get("id", "Unknown"), |
|
"admission_date": datetime.now().strftime("%Y-%m-%d"), |
|
"physician": "Dr. AI Provider", |
|
} |
|
|
|
output_dir = tempfile.mkdtemp() |
|
pdf_path = generate_discharge_summary( |
|
patient_info, llm_content, output_dir |
|
) |
|
|
|
return pdf_path, "PDF generated successfully with AI Content" |
|
|
|
except Exception as e: |
|
return None, f"Error generating PDF with AI content: {str(e)}" |
|
|
|
|
|
def extract_auth_code_from_url(redirected_url): |
|
"""Extracts the authorization code from the redirected URL.""" |
|
try: |
|
parsed_url = urlparse(redirected_url) |
|
query_params = parse_qs(parsed_url.query) |
|
if "code" in query_params: |
|
return query_params["code"][0], None |
|
else: |
|
return None, "Authorization code not found in URL." |
|
except Exception as e: |
|
return None, f"Error parsing URL: {e}" |
|
|
|
|
|
|
|
CALLBACK_MANAGER = CallbackManager( |
|
redirect_uri="https://multitransformer-discharge-guard.hf.space/callback", |
|
client_secret=None, |
|
) |
|
|
|
|
|
cyberpunk_theme = gr.themes.Monochrome( |
|
primary_hue="cyan", |
|
secondary_hue="pink", |
|
neutral_hue="slate", |
|
font=["Source Code Pro", "monospace"], |
|
font_mono=["Source Code Pro", "monospace"], |
|
) |
|
|
|
|
|
with gr.Blocks(theme=cyberpunk_theme) as demo: |
|
gr.Markdown( |
|
"<h1 style='color:#00FFFF; text-shadow: 0 0 5px #00FFFF;'>Discharge Guard <span style='color:#FF00FF; text-shadow: 0 0 5px #FF00FF;'>Cyber</span></h1>" |
|
) |
|
|
|
with gr.Tab("Authenticate with MeldRx", elem_classes="cyberpunk-tab"): |
|
gr.Markdown( |
|
"<h2 style='color:#00FFFF; text-shadow: 0 0 3px #00FFFF;'>SMART on FHIR Authentication</h2>" |
|
) |
|
auth_url_output = gr.Textbox( |
|
label="Authorization URL", |
|
value=CALLBACK_MANAGER.get_auth_url(), |
|
interactive=False, |
|
) |
|
gr.Markdown( |
|
"<p style='color:#A9A9A9;'>Copy the URL above, open it in a browser, log in, and paste the <span style='color:#00FFFF;'>entire redirected URL</span> from your browser's address bar below.</p>" |
|
) |
|
redirected_url_input = gr.Textbox(label="Redirected URL") |
|
extract_code_button = gr.Button( |
|
"Extract Authorization Code", elem_classes="cyberpunk-button" |
|
) |
|
extracted_code_output = gr.Textbox( |
|
label="Extracted Authorization Code", interactive=False |
|
) |
|
|
|
auth_code_input = gr.Textbox( |
|
label="Authorization Code (from above, or paste manually if extraction fails)", |
|
interactive=True, |
|
) |
|
auth_submit = gr.Button( |
|
"Submit Code for Authentication", elem_classes="cyberpunk-button" |
|
) |
|
auth_result = gr.HTML(label="Authentication Result") |
|
|
|
patient_data_button = gr.Button( |
|
"Fetch Patient Data", elem_classes="cyberpunk-button" |
|
) |
|
patient_data_output = gr.Textbox(label="Patient Data", lines=10) |
|
|
|
|
|
meldrx_pdf_button = gr.Button( |
|
"Generate PDF from MeldRx Data (No AI)", elem_classes="cyberpunk-button" |
|
) |
|
meldrx_pdf_status = gr.Textbox( |
|
label="PDF Generation Status (No AI)" |
|
) |
|
meldrx_pdf_download = gr.File( |
|
label="Download Generated PDF (No AI)" |
|
) |
|
|
|
def process_redirected_url(redirected_url): |
|
"""Processes the redirected URL to extract and display the authorization code.""" |
|
auth_code, error_message = extract_auth_code_from_url(redirected_url) |
|
if auth_code: |
|
return auth_code, "<span style='color:#00FF7F;'>Authorization code extracted!</span>" |
|
else: |
|
return "", f"<span style='color:#FF4500;'>Could not extract authorization code.</span> {error_message or ''}" |
|
|
|
extract_code_button.click( |
|
fn=process_redirected_url, |
|
inputs=redirected_url_input, |
|
outputs=[ |
|
extracted_code_output, |
|
auth_result, |
|
], |
|
) |
|
|
|
auth_submit.click( |
|
fn=CALLBACK_MANAGER.set_auth_code, |
|
inputs=extracted_code_output, |
|
outputs=auth_result, |
|
) |
|
|
|
with gr.Tab( |
|
"Patient Dashboard", elem_classes="cyberpunk-tab" |
|
): |
|
gr.Markdown( |
|
"<h2 style='color:#00FFFF; text-shadow: 0 0 3px #00FFFF;'>Patient Data</h2>" |
|
) |
|
dashboard_output = gr.HTML( |
|
"<p style='color:#A9A9A9;'>Fetch patient data from the Authentication tab first.</p>" |
|
) |
|
|
|
refresh_btn = gr.Button( |
|
"Refresh Data", elem_classes="cyberpunk-button" |
|
) |
|
|
|
|
|
def update_dashboard(): |
|
try: |
|
data = CALLBACK_MANAGER.get_patient_data() |
|
if ( |
|
data.startswith("<span style='color:#FF8C00;'>Not authenticated") |
|
or data.startswith("<span style='color:#DC143C;'>Failed") |
|
or data.startswith("<span style='color:#FF6347;'>Error") |
|
): |
|
return f"<p style='color:#FF8C00;'>{data}</p>" |
|
|
|
try: |
|
|
|
patients_data = json.loads(data) |
|
patients = [] |
|
|
|
|
|
for entry in patients_data.get("entry", []): |
|
resource = entry.get("resource", {}) |
|
if resource.get("resourceType") == "Patient": |
|
patients.append(resource) |
|
|
|
|
|
html = "<h3 style='color:#00FFFF; text-shadow: 0 0 2px #00FFFF;'>Patients</h3>" |
|
for patient in patients: |
|
|
|
name = patient.get("name", [{}])[0] |
|
given = " ".join(name.get("given", ["Unknown"])) |
|
family = name.get("family", "Unknown") |
|
|
|
|
|
gender = patient.get("gender", "unknown").capitalize() |
|
birth_date = patient.get("birthDate", "Unknown") |
|
|
|
|
|
html += f""" |
|
<div style="border: 1px solid #00FFFF; padding: 10px; margin: 10px 0; border-radius: 5px; background-color: #222; box-shadow: 0 0 5px #00FFFF;"> |
|
<h4 style='color:#00FFFF;'>{given} {family}</h4> |
|
<p style='color:#A9A9A9;'><strong>Gender:</strong> <span style='color:#00FFFF;'>{gender}</span></p> |
|
<p style='color:#A9A9A9;'><strong>Birth Date:</strong> <span style='color:#00FFFF;'>{birth_date}</span></p> |
|
<p style='color:#A9A9A9;'><strong>ID:</strong> <span style='color:#00FFFF;'>{patient.get("id", "Unknown")}</span></p> |
|
</div> |
|
""" |
|
|
|
return html |
|
except Exception as e: |
|
return f"<p style='color:#FF6347;'>Error parsing patient data: {str(e)}</p>" |
|
except Exception as e: |
|
return f"<p style='color:#FF6347;'>Error fetching patient data: {str(e)}</p>" |
|
|
|
refresh_btn.click(fn=update_dashboard, inputs=None, outputs=dashboard_output) |
|
|
|
with gr.Tab("Discharge Form", elem_classes="cyberpunk-tab"): |
|
gr.Markdown( |
|
"<h2 style='color:#00FFFF; text-shadow: 0 0 3px #00FFFF;'>Patient Details</h2>" |
|
) |
|
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( |
|
"<h2 style='color:#00FFFF; text-shadow: 0 0 3px #00FFFF;'>Primary Healthcare Professional Details</h2>" |
|
) |
|
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="Doctor's 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( |
|
"<h2 style='color:#00FFFF; text-shadow: 0 0 3px #00FFFF;'>Admission and Discharge Details</h2>" |
|
) |
|
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( |
|
"<h2 style='color:#00FFFF; text-shadow: 0 0 3px #00FFFF;'>Diagnosis & Procedures</h2>" |
|
) |
|
diagnosis = gr.Textbox(label="Diagnosis") |
|
procedures = gr.Textbox(label="Operation & Procedures") |
|
gr.Markdown( |
|
"<h2 style='color:#00FFFF; text-shadow: 0 0 3px #00FFFF;'>Medication Details</h2>" |
|
) |
|
medications = gr.Textbox(label="Medication on Discharge") |
|
gr.Markdown( |
|
"<h2 style='color:#00FFFF; text-shadow: 0 0 3px #00FFFF;'>Prepared By</h2>" |
|
) |
|
with gr.Row(): |
|
preparer_name = gr.Textbox(label="Name") |
|
preparer_job_title = gr.Textbox(label="Job Title") |
|
|
|
|
|
with gr.Row(): |
|
submit_display = gr.Button( |
|
"Display Form", elem_classes="cyberpunk-button" |
|
) |
|
submit_pdf = gr.Button( |
|
"Generate PDF (No AI)", elem_classes="cyberpunk-button" |
|
) |
|
|
|
|
|
form_output = gr.HTML() |
|
pdf_output = gr.File( |
|
label="Download PDF (No AI)" |
|
) |
|
|
|
|
|
submit_display.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=form_output, |
|
) |
|
|
|
|
|
submit_pdf.click( |
|
generate_pdf_from_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=pdf_output, |
|
) |
|
|
|
with gr.Tab( |
|
"Medical File Analysis", elem_classes="cyberpunk-tab" |
|
): |
|
gr.Markdown( |
|
"<h2 style='color:#00FFFF; text-shadow: 0 0 3px #00FFFF;'>Analyze Medical Files with Discharge Guard AI</h2>" |
|
) |
|
with gr.Column(): |
|
dicom_file = gr.File( |
|
file_types=[".dcm"], label="Upload DICOM File (.dcm)" |
|
) |
|
dicom_ai_output = gr.Textbox(label="DICOM Analysis Report", lines=5) |
|
analyze_dicom_button = gr.Button( |
|
"Analyze DICOM with AI", elem_classes="cyberpunk-button" |
|
) |
|
|
|
hl7_file = gr.File(file_types=[".hl7"], label="Upload HL7 File (.hl7)") |
|
hl7_ai_output = gr.Textbox(label="HL7 Analysis Report", lines=5) |
|
analyze_hl7_button = gr.Button( |
|
"Analyze HL7 with AI", elem_classes="cyberpunk-button" |
|
) |
|
|
|
xml_file = gr.File(file_types=[".xml"], label="Upload XML File (.xml)") |
|
xml_ai_output = gr.Textbox(label="XML Analysis Report", lines=5) |
|
analyze_xml_button = gr.Button( |
|
"Analyze XML with AI", elem_classes="cyberpunk-button" |
|
) |
|
|
|
ccda_file = gr.File( |
|
file_types=[".xml", ".cda", ".ccd"], |
|
label="Upload CCDA File (.xml, .cda, .ccd)", |
|
) |
|
ccda_ai_output = gr.Textbox(label="CCDA Analysis Report", lines=5) |
|
analyze_ccda_button = gr.Button( |
|
"Analyze CCDA with AI", elem_classes="cyberpunk-button" |
|
) |
|
|
|
ccd_file = gr.File( |
|
file_types=[".ccd"], |
|
label="Upload CCD File (.ccd)", |
|
) |
|
ccd_ai_output = gr.Textbox( |
|
label="CCD Analysis Report", lines=5 |
|
) |
|
analyze_ccd_button = gr.Button( |
|
"Analyze CCD with AI", elem_classes="cyberpunk-button" |
|
) |
|
pdf_file = gr.File(file_types=[".pdf"], label="Upload PDF File (.pdf)") |
|
pdf_ai_output = gr.Textbox(label="PDF Analysis Report", lines=5) |
|
analyze_pdf_button = gr.Button( |
|
"Analyze PDF with AI", elem_classes="cyberpunk-button" |
|
) |
|
|
|
csv_file = gr.File(file_types=[".csv"], label="Upload CSV File (.csv)") |
|
csv_ai_output = gr.Textbox(label="CSV Analysis Report", lines=5) |
|
analyze_csv_button = gr.Button( |
|
"Analyze CSV with AI", elem_classes="cyberpunk-button" |
|
) |
|
|
|
|
|
analyze_dicom_button.click( |
|
analyze_dicom_file_with_ai, |
|
inputs=dicom_file, |
|
outputs=dicom_ai_output, |
|
) |
|
analyze_hl7_button.click( |
|
analyze_hl7_file_with_ai, |
|
inputs=hl7_file, |
|
outputs=hl7_ai_output, |
|
) |
|
analyze_xml_button.click( |
|
analyze_cda_xml_file_with_ai, |
|
inputs=xml_file, |
|
outputs=xml_ai_output, |
|
) |
|
analyze_ccda_button.click( |
|
analyze_cda_xml_file_with_ai, |
|
inputs=ccda_file, |
|
outputs=ccda_ai_output, |
|
) |
|
analyze_ccd_button.click( |
|
analyze_cda_xml_file_with_ai, |
|
inputs=ccd_file, |
|
outputs=ccd_ai_output, |
|
) |
|
analyze_pdf_button.click( |
|
analyze_pdf_file_with_ai, inputs=pdf_file, outputs=pdf_ai_output |
|
) |
|
analyze_csv_button.click( |
|
analyze_csv_file_with_ai, inputs=csv_file, outputs=csv_ai_output |
|
) |
|
|
|
with gr.Tab( |
|
"One-Click Discharge Paper (AI)", elem_classes="cyberpunk-tab" |
|
): |
|
gr.Markdown( |
|
"<h2 style='color:#00FFFF; text-shadow: 0 0 3px #00FFFF;'>One-Click Medical Discharge Paper Generation with AI Content</h2>" |
|
) |
|
one_click_ai_pdf_button = gr.Button( |
|
"Generate Discharge Paper with AI (One-Click)", |
|
elem_classes="cyberpunk-button", |
|
) |
|
one_click_ai_pdf_status = gr.Textbox( |
|
label="Discharge Paper Generation Status (AI)" |
|
) |
|
one_click_ai_pdf_download = gr.File( |
|
label="Download Discharge Paper (AI)" |
|
) |
|
|
|
one_click_ai_pdf_button.click( |
|
generate_discharge_paper_one_click, |
|
inputs=[], |
|
outputs=[one_click_ai_pdf_download, one_click_ai_pdf_status], |
|
) |
|
|
|
|
|
patient_data_button.click( |
|
fn=CALLBACK_MANAGER.get_patient_data, inputs=None, outputs=patient_data_output |
|
) |
|
|
|
|
|
refresh_btn.click(fn=update_dashboard, inputs=None, outputs=dashboard_output) |
|
|
|
|
|
meldrx_pdf_button.click( |
|
fn=generate_pdf_from_meldrx, |
|
inputs=patient_data_output, |
|
outputs=[meldrx_pdf_download, meldrx_pdf_status], |
|
) |
|
|
|
|
|
patient_data_button.click( |
|
fn=update_dashboard, inputs=None, outputs=dashboard_output |
|
) |
|
|
|
|
|
|
|
demo.launch(ssr_mode=False) |