Spaces:
Runtime error
Runtime error
updated UI code ✅✅
Browse files385 unmodified lines3863873883893903913925 unmodified lines3983994004014024034041 unmodified line4064074084094104114124134144154164174184194204214224234244252 unmodified lines4284294304314324334344354364374384394404414424434444454464474484494504514524 unmodified lines4574584594604614624634644654664674684694704714724734744751 unmodified line4774784794804814824834844854864874882 unmodified lines4914924934944954964974984995005015025035045055065075085095105115125135145154 unmodified lines5205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655663 unmodified lines5705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086094 unmodified lines6146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807811 unmodified line7837847857867877887893 unmodified lines7937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059061 unmodified line9089099109119129139149159169179189199209219229239249259261 unmodified line9289299309319329339341 unmodified line9369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899902 unmodified lines993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510465 unmodified lines1052105310541055105610571058105910601061106210631064106510661 unmodified line10681069107010711072107310741075107610771078107910802 unmodified lines10831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255385 unmodified linesimport loggingimport osimport sysimport tempfilefrom pathlib import Pathimport requestsimport gradio as gr5 unmodified linestry:from .config import get_flask_urls, get_doctors_page_urls, TIMEOUT_SETTINGSexcept ImportError:# Fallback configuration if config file is not availabledef get_flask_urls():return ["http://127.0.0.1:600/complete_appointment",1 unmodified line"https://your-flask-app-domain.com/complete_appointment","http://your-flask-app-ip:600/complete_appointment"]def get_doctors_page_urls():return {"local": "http://127.0.0.1:600/doctors","production": "https://your-flask-app-domain.com/doctors"}TIMEOUT_SETTINGS = {"connection_timeout": 5, "request_timeout": 10}# Add parent directory to pathparent_dir = os.path.dirname(os.path.abspath(__file__))sys.path.append(parent_dir)# Configure logginglogging.basicConfig(level=logging.INFO,format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",2 unmodified lineslogger = logging.getLogger(__name__)class MediSyncApp:"""Main application class for the MediSync multi-modal medical analysis system."""def __init__(self):"""Initialize the application and load models."""self.logger = logging.getLogger(__name__)self.logger.info("Initializing MediSync application")self._temp_files = [] # Track temporary files for cleanupself.fusion_model = Noneself.image_model = Noneself.text_model = Nonedef __del__(self):"""Cleanup temporary files on object destruction."""self.cleanup_temp_files()def cleanup_temp_files(self):"""Clean up temporary files."""for temp_file in self._temp_files:try:if os.path.exists(temp_file):4 unmodified linesself._temp_files = []def load_models(self):"""Load models if not already loaded.Returns:bool: True if models loaded successfully, False otherwise"""if self.fusion_model is not None:return Truetry:self.logger.info("Loading models...")# For now, we'll create a simple mock implementation# You can replace this with your actual model loading codeself.logger.info("Models loaded successfully (mock implementation)")return Trueexcept Exception as e:1 unmodified linereturn Falsedef enhance_image(self, image):"""Enhance the uploaded image."""if image is None:return Nonetry:# Simple image enhancement (you can replace with actual enhancement logic)enhanced_image = imageself.logger.info("Image enhanced successfully")return enhanced_image2 unmodified linesreturn imagedef analyze_image(self, image):"""Analyze a medical image.Args:image: Image file uploaded through GradioReturns:tuple: (image, image_results_html, plot_as_html)"""if image is None:return None, "Please upload an image first.", Noneif not self.load_models():return image, "Error: Models not loaded properly.", Nonetry:self.logger.info("Analyzing image")# Mock analysis results (replace with actual model inference)results = {"primary_finding": "Normal chest X-ray","confidence": 0.85,4 unmodified lines("Cardiomegaly", 0.05)]}# Create visualizationfig = self.plot_image_prediction(image,results.get("predictions", []),f"Primary Finding: {results.get('primary_finding', 'Unknown')}")# Convert to HTML for displayplot_html = self.fig_to_html(fig)plt.close(fig) # Clean up matplotlib figure# Format results as HTMLhtml_result = self.format_image_results(results)return image, html_result, plot_htmlexcept Exception as e:self.logger.error(f"Error in image analysis: {e}")return image, f"Error analyzing image: {str(e)}", Nonedef analyze_text(self, text):"""Analyze medical report text.Args:text: Medical report textReturns:tuple: (processed_text, text_results_html, plot_as_html)"""if not text or text.strip() == "":return "", "Please enter medical report text.", Noneif not self.load_models():return text, "Error: Models not loaded properly.", Nonetry:self.logger.info("Analyzing text")# Mock text analysis results (replace with actual model inference)results = {"entities": [{"text": "chest X-ray", "type": "PROCEDURE", "confidence": 0.95},3 unmodified lines"sentiment": "neutral","key_findings": ["Normal heart size", "Clear lungs", "8mm nodular opacity"]}# Format results as HTMLhtml_result = self.format_text_results(results)# Create entity visualizationplot_html = self.create_entity_visualization(results["entities"])return text, html_result, plot_htmlexcept Exception as e:self.logger.error(f"Error in text analysis: {e}")return text, f"Error analyzing text: {str(e)}", Nonedef analyze_multimodal(self, image, text):"""Analyze both image and text together.Args:image: Medical imagetext: Medical report textReturns:tuple: (results_html, plot_as_html)"""if image is None and (not text or text.strip() == ""):return "Please provide either an image or text for analysis.", Noneif not self.load_models():return "Error: Models not loaded properly.", Nonetry:self.logger.info("Performing multimodal analysis")# Mock multimodal analysis results (replace with actual model inference)results = {"combined_finding": "Normal chest X-ray with minor findings","confidence": 0.92,4 unmodified lines"Monitor for any changes in symptoms"]}# Format results as HTMLhtml_result = self.format_multimodal_results(results)# Create combined visualizationplot_html = self.create_multimodal_visualization(results)return html_result, plot_htmlexcept Exception as e:self.logger.error(f"Error in multimodal analysis: {e}")return f"Error in multimodal analysis: {str(e)}", Nonedef format_image_results(self, results):"""Format image analysis results as HTML."""html_result = f"""<div style="background-color: #f8f9fa; padding: 20px; border-radius: 10px; margin: 10px 0;"><h2 style="color: #007bff;">X-ray Analysis Results</h2><p><strong>Primary Finding:</strong> {results.get("primary_finding", "Unknown")}</p><p><strong>Confidence:</strong> {results.get("confidence", 0):.1%}</p><p><strong>Abnormality Detected:</strong> {"Yes" if results.get("has_abnormality", False) else "No"}</p><h3>Top Predictions:</h3><ul>"""for label, prob in results.get("predictions", [])[:5]:html_result += f"<li>{label}: {prob:.1%}</li>"html_result += "</ul></div>"return html_resultdef format_text_results(self, results):"""Format text analysis results as HTML."""html_result = f"""<div style="background-color: #f8f9fa; padding: 20px; border-radius: 10px; margin: 10px 0;"><h2 style="color: #28a745;">Text Analysis Results</h2><p><strong>Sentiment:</strong> {results.get("sentiment", "Unknown").title()}</p><h3>Key Findings:</h3><ul>"""for finding in results.get("key_findings", []):html_result += f"<li>{finding}</li>"html_result += "</ul>"html_result += "<h3>Extracted Entities:</h3><ul>"for entity in results.get("entities", [])[:5]:html_result += f"<li><strong>{entity['text']}</strong> ({entity['type']}) - {entity['confidence']:.1%}</li>"html_result += "</ul></div>"return html_resultdef format_multimodal_results(self, results):"""Format multimodal analysis results as HTML."""html_result = f"""<div style="background-color: #f8f9fa; padding: 20px; border-radius: 10px; margin: 10px 0;"><h2 style="color: #6f42c1;">Multimodal Analysis Results</h2><p><strong>Combined Finding:</strong> {results.get("combined_finding", "Unknown")}</p><p><strong>Overall Confidence:</strong> {results.get("confidence", 0):.1%}</p><h3>Image Contribution:</h3><p>{results.get("image_contribution", "No image analysis available")}</p><h3>Text Contribution:</h3><p>{results.get("text_contribution", "No text analysis available")}</p><h3>Recommendations:</h3><ul>"""for rec in results.get("recommendations", []):html_result += f"<li>{rec}</li>"html_result += "</ul></div>"return html_resultdef plot_image_prediction(self, image, predictions, title):"""Create visualization for image predictions."""fig, ax = plt.subplots(figsize=(10, 6))ax.imshow(image)ax.set_title(title, fontsize=14, fontweight='bold')ax.axis('off')return figdef create_entity_visualization(self, entities):"""Create visualization for text entities."""if not entities:return "<p>No entities found in text.</p>"fig, ax = plt.subplots(figsize=(10, 6))entity_types = {}for entity in entities:entity_type = entity['type']if entity_type not in entity_types:entity_types[entity_type] = 0entity_types[entity_type] += 1if entity_types:ax.bar(entity_types.keys(), entity_types.values(), color='skyblue')ax.set_title('Entity Types Found in Text', fontsize=14, fontweight='bold')ax.set_ylabel('Count')plt.xticks(rotation=45)return self.fig_to_html(fig)def create_multimodal_visualization(self, results):"""Create visualization for multimodal results."""fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6))# Confidence visualizationconfidence = results.get("confidence", 0)ax1.pie([confidence, 1-confidence], labels=['Confidence', 'Uncertainty'],colors=['lightgreen', 'lightcoral'], autopct='%1.1f%%')ax1.set_title('Analysis Confidence', fontweight='bold')# Recommendations countrecommendations = results.get("recommendations", [])ax2.bar(['Recommendations'], [len(recommendations)], color='lightblue')ax2.set_title('Number of Recommendations', fontweight='bold')ax2.set_ylabel('Count')plt.tight_layout()return self.fig_to_html(fig)def fig_to_html(self, fig):"""Convert matplotlib figure to HTML."""import ioimport base64buf = io.BytesIO()fig.savefig(buf, format='png', bbox_inches='tight', dpi=100)buf.seek(0)img_str = base64.b64encode(buf.read()).decode()buf.close()return f'<img src="data:image/png;base64,{img_str}" style="max-width: 100%; height: auto;"/>'def complete_appointment(appointment_id):"""Complete an appointment by calling the Flask API.Args:appointment_id: The appointment ID to completeReturns:dict: Response from the API"""try:# Get Flask URLs from configurationflask_urls = get_flask_urls()payload = {"appointment_id": appointment_id}for flask_api_url in flask_urls:try:logger.info(f"Trying to connect to: {flask_api_url}")response = requests.post(flask_api_url, json=payload, timeout=TIMEOUT_SETTINGS["connection_timeout"])if response.status_code == 200:return {"status": "success", "message": "Appointment completed successfully"}elif response.status_code == 404:1 unmodified lineelse:logger.warning(f"Unexpected response from {flask_api_url}: {response.status_code}")continueexcept requests.exceptions.ConnectionError:logger.warning(f"Connection failed to {flask_api_url}")continue3 unmodified linesexcept Exception as e:logger.warning(f"Error with {flask_api_url}: {e}")continue# If all URLs fail, return a helpful error messagereturn {"status": "error","message": "Cannot connect to Flask app. Please ensure the Flask app is running and accessible."}except Exception as e:logger.error(f"Error completing appointment: {e}")return {"status": "error", "message": f"Error: {str(e)}"}def create_interface():"""Create and launch the Gradio interface."""app = MediSyncApp()# Example medical report for demoexample_report = """CHEST X-RAY EXAMINATIONCLINICAL HISTORY: 55-year-old male with cough and fever.FINDINGS: The heart size is at the upper limits of normal. The lungs are clear without focal consolidation,effusion, or pneumothorax. There is mild prominence of the pulmonary vasculature. No pleural effusion is seen.There is a small nodular opacity noted in the right lower lobe measuring approximately 8mm, which is suspiciousand warrants further investigation. The mediastinum is unremarkable. The visualized bony structures show no acute abnormalities.IMPRESSION:1. Mild cardiomegaly.2. 8mm nodular opacity in the right lower lobe, recommend follow-up CT for further evaluation.3. No acute pulmonary parenchymal abnormality.RECOMMENDATIONS: Follow-up chest CT to further characterize the nodular opacity in the right lower lobe."""# Get sample image path if availablesample_images_dir = Path(parent_dir) / "data" / "sample"sample_images = list(sample_images_dir.glob("*.png")) + list(sample_images_dir.glob("*.jpg"))sample_image_path = Noneif sample_images:sample_image_path = str(sample_images[0])# Define interfacewith gr.Blocks(title="MediSync: Multi-Modal Medical Analysis System", theme=gr.themes.Soft()) as interface:gr.Markdown("""# MediSync: Multi-Modal Medical Analysis SystemThis AI-powered healthcare solution combines X-ray image analysis with patient report text processingto provide comprehensive medical insights.## How to Use1. Upload a chest X-ray image2. Enter the corresponding medical report text3. Choose the analysis type: image-only, text-only, or multimodal (combined)4. Click "End Consultation" when finished to complete your appointment""")# Add appointment ID input with Python-based populationwith gr.Row():# Get appointment ID from URL parameters if availableimport urllib.parsetry:# This will be set by JavaScript, but we can also try to get it server-sideurl_params = {}if hasattr(gr, 'get_current_url'):current_url = gr.get_current_url()if current_url:parsed = urllib.parse.urlparse(current_url)url_params = urllib.parse.parse_qs(parsed.query)default_appointment_id = url_params.get('appointment_id', [''])[0]except:default_appointment_id = ""appointment_id_input = gr.Textbox(label="Appointment ID",placeholder="Enter your appointment ID here...",info="This will be automatically populated if you came from the doctors page",value=default_appointment_id)with gr.Tab("Multimodal Analysis"):with gr.Row():with gr.Column():multi_img_input = gr.Image(label="Upload X-ray Image", type="pil")multi_img_enhance = gr.Button("Enhance Image")multi_text_input = gr.Textbox(label="Enter Medical Report Text",placeholder="Enter the radiologist's report text here...",lines=10,value=example_report if sample_image_path is None else None,)multi_analyze_btn = gr.Button("Analyze Image & Text", variant="primary")with gr.Column():multi_results = gr.HTML(label="Analysis Results")multi_plot = gr.HTML(label="Visualization")# Set up examples if sample image existsif sample_image_path:gr.Examples(examples=[[sample_image_path, example_report]],1 unmodified linelabel="Example X-ray and Report",)with gr.Tab("Image Analysis"):with gr.Row():with gr.Column():img_input = gr.Image(label="Upload X-ray Image", type="pil")img_enhance = gr.Button("Enhance Image")img_analyze_btn = gr.Button("Analyze Image", variant="primary")with gr.Column():img_output = gr.Image(label="Processed Image")img_results = gr.HTML(label="Analysis Results")img_plot = gr.HTML(label="Visualization")# Set up example if sample image existsif sample_image_path:gr.Examples(examples=[[sample_image_path]],1 unmodified linelabel="Example X-ray Image",)with gr.Tab("Text Analysis"):with gr.Row():with gr.Column():text_input = gr.Textbox(1 unmodified lineplaceholder="Enter the radiologist's report text here...",lines=10,value=example_report,)text_analyze_btn = gr.Button("Analyze Text", variant="primary")with gr.Column():text_output = gr.Textbox(label="Processed Text")text_results = gr.HTML(label="Analysis Results")text_plot = gr.HTML(label="Entity Visualization")# Set up examplegr.Examples(examples=[[example_report]],inputs=[text_input],label="Example Medical Report",)# End Consultation Sectionwith gr.Row():with gr.Column():end_consultation_btn = gr.Button("End Consultation",variant="stop",size="lg",elem_classes=["end-consultation-btn"])end_consultation_status = gr.HTML(label="Status")with gr.Tab("About"):gr.Markdown("""## About MediSyncMediSync is an AI-powered healthcare solution that uses multi-modal analysis to provide comprehensive insights from medical images and reports.### Key Features- **X-ray Image Analysis**: Detects abnormalities in chest X-rays using pre-trained vision models- **Medical Report Processing**: Extracts key information from patient reports using NLP models- **Multi-modal Integration**: Combines insights from both image and text data for more accurate analysis### Models Used- **X-ray Analysis**: facebook/deit-base-patch16-224-medical-cxr- **Medical Text Analysis**: medicalai/ClinicalBERT### Important DisclaimerThis tool is for educational and research purposes only. It is not intended to provide medical advice or replace professional healthcare. Always consult with qualified healthcare providers for medical decisions.""")# Set up event handlersmulti_img_enhance.click(app.enhance_image, inputs=multi_img_input, outputs=multi_img_input)2 unmodified linesinputs=[multi_img_input, multi_text_input],outputs=[multi_results, multi_plot],)img_enhance.click(app.enhance_image, inputs=img_input, outputs=img_output)img_analyze_btn.click(app.analyze_image,inputs=img_input,outputs=[img_output, img_results, img_plot],)text_analyze_btn.click(app.analyze_text,inputs=text_input,outputs=[text_output, text_results, text_plot],)# End consultation handlerdef handle_end_consultation(appointment_id):if not appointment_id or appointment_id.strip() == "":return "<div style='color: red; padding: 10px; background-color: #ffe6e6; border-radius: 5px;'>Please enter your appointment ID first.</div>"# Try to complete the appointmentresult = complete_appointment(appointment_id.strip())if result["status"] == "success":# Get doctors page URLs from configurationdoctors_urls = get_doctors_page_urls()# Create success message with redirect buttonhtml_response = f"""<div style='color: green; padding: 15px; background-color: #e6ffe6; border-radius: 5px; margin: 10px 0;'><h3>✅ Consultation Completed Successfully!</h3><p>{result['message']}</p><p>Your appointment has been marked as completed.</p><button onclick="window.open('{doctors_urls['local']}', '_blank')"style="background-color: #007bff; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; margin-top: 10px;">Return to Doctors Page (Local)</button><button onclick="window.open('{doctors_urls['production']}', '_blank')"style="background-color: #28a745; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; margin-top: 10px; margin-left: 10px;">Return to Doctors Page (Production)</button></div>"""else:# Handle connection failure gracefullyif "Cannot connect to Flask app" in result['message']:# Show a helpful message with manual completion instructionshtml_response = f"""<div style='color: orange; padding: 15px; background-color: #fff3cd; border-radius: 5px; margin: 10px 0;'><h3>⚠️ Consultation Ready to Complete</h3><p>Your consultation analysis is complete! However, we cannot automatically mark your appointment as completed because the Flask app is not accessible from this environment.</p><p><strong>Appointment ID:</strong> {appointment_id.strip()}</p>5 unmodified lines</ol><div style="margin-top: 15px;"><button onclick="window.open('http://127.0.0.1:600/complete_appointment_manual?appointment_id={appointment_id.strip()}', '_blank')"style="background-color: #007bff; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; margin-right: 10px;">Complete Appointment</button><button onclick="window.open('http://127.0.0.1:600/doctors', '_blank')"style="background-color: #28a745; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; margin-right: 10px;">Return to Doctors Page</button><button onclick="navigator.clipboard.writeText('{appointment_id.strip()}')"style="background-color: #6c757d; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer;">Copy Appointment ID</button></div>1 unmodified line"""else:html_response = f"""<div style='color: red; padding: 15px; background-color: #ffe6e6; border-radius: 5px; margin: 10px 0;'><h3>❌ Error Completing Consultation</h3><p>{result['message']}</p><p>Please try again or contact support if the problem persists.</p></div>"""return html_responseend_consultation_btn.click(2 unmodified linesoutputs=[end_consultation_status])# Add custom CSS and JavaScript for better styling and functionalitygr.HTML("""<style>.end-consultation-btn {background-color: #dc3545 !important;border-color: #dc3545 !important;color: white !important;font-weight: bold !important;}.end-consultation-btn:hover {background-color: #c82333 !important;border-color: #bd2130 !important;}</style><script>// Function to get URL parametersfunction getUrlParameter(name) {name = name.replace(/[[]/, '\\[').replace(/[\]]/, '\\]');var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');var results = regex.exec(location.search);return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));}// Function to populate appointment ID from URLfunction populateAppointmentId() {var appointmentId = getUrlParameter('appointment_id');console.log('Found appointment ID:', appointmentId);if (appointmentId) {// Try multiple methods to find and populate the appointment ID inputvar success = false;// Method 1: Try by specific element IDvar elementById = document.getElementById('appointment_id_input');if (elementById) {elementById.value = appointmentId;var event = new Event('input', { bubbles: true });elementById.dispatchEvent(event);console.log('Set appointment ID by ID to:', appointmentId);success = true;}// Method 2: Try by placeholder textif (!success) {var selectors = ['input[placeholder*="appointment ID"]','input[placeholder*="appointment_id"]','input[placeholder*="Appointment ID"]','textarea[placeholder*="appointment ID"]','textarea[placeholder*="appointment_id"]','textarea[placeholder*="Appointment ID"]'];for (var selector of selectors) {var elements = document.querySelectorAll(selector);for (var element of elements) {console.log('Found element by placeholder:', element);element.value = appointmentId;var event = new Event('input', { bubbles: true });element.dispatchEvent(event);console.log('Set appointment ID by placeholder to:', appointmentId);success = true;break;}if (success) break;}}// Method 3: Try by label textif (!success) {var labels = document.querySelectorAll('label');for (var label of labels) {if (label.textContent && label.textContent.toLowerCase().includes('appointment id')) {var input = label.nextElementSibling;if (input && (input.tagName === 'INPUT' || input.tagName === 'TEXTAREA')) {input.value = appointmentId;var event = new Event('input', { bubbles: true });input.dispatchEvent(event);console.log('Set appointment ID by label to:', appointmentId);success = true;break;}}}}// Method 4: Try by Gradio component attributesif (!success) {var gradioInputs = document.querySelectorAll('[data-testid="textbox"]');for (var input of gradioInputs) {var label = input.closest('.form').querySelector('label');if (label && label.textContent.toLowerCase().includes('appointment id')) {input.value = appointmentId;var event = new Event('input', { bubbles: true });input.dispatchEvent(event);console.log('Set appointment ID by Gradio component to:', appointmentId);success = true;break;}}}if (!success) {console.log('Could not find appointment ID input field');// Log all input elements for debuggingvar allInputs = document.querySelectorAll('input, textarea');console.log('All input elements found:', allInputs.length);for (var i = 0; i < allInputs.length; i++) {console.log('Input', i, ':', allInputs[i].placeholder, allInputs[i].id, allInputs[i].className);}}} else {console.log('No appointment ID found in URL');}return success;}// Function to wait for Gradio to be readyfunction waitForGradio() {if (typeof gradio !== 'undefined' && gradio) {console.log('Gradio detected, waiting for load...');setTimeout(function() {populateAppointmentId();// Also try again after a longer delaysetTimeout(populateAppointmentId, 2000);}, 1000);} else {console.log('Gradio not detected, trying direct population...');populateAppointmentId();// Try again after a delaysetTimeout(populateAppointmentId, 1000);}}// Run when page loadsdocument.addEventListener('DOMContentLoaded', function() {console.log('DOM loaded, attempting to populate appointment ID...');waitForGradio();});// Also run when window loadswindow.addEventListener('load', function() {console.log('Window loaded, attempting to populate appointment ID...');setTimeout(waitForGradio, 500);});// Monitor for dynamic content changesvar observer = new MutationObserver(function(mutations) {mutations.forEach(function(mutation) {if (mutation.type === 'childList') {setTimeout(populateAppointmentId, 100);}});});// Start observingobserver.observe(document.body, {childList: true,subtree: true});</script>""")# Run the interfaceinterface.launch()if __name__ == "__main__":create_interface()385 unmodified lines3863873883893903915 unmodified lines3973983994004014021 unmodified line4044054064074084094104114124134144154164174184192 unmodified lines4224234244254264274284294304314324334344354364374384394 unmodified lines4444454464474484494504514524531 unmodified line4554564574584594604614624632 unmodified lines4664674684694704714724734744754764774 unmodified lines4824834844854864874884894904914924934944954964974984995005015025035045055065073 unmodified lines5115125135145155165175185195205215225235245255265275285295304 unmodified lines5355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526531 unmodified line6556566576586596603 unmodified lines6646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458461 unmodified line8488498508518528538548558568578588598608618628631 unmodified line8658668678688698708711 unmodified line8738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299302 unmodified lines9339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749755 unmodified lines9819829839849859869879889899909919929939949951 unmodified line9979989991000100110021003100410051006100710082 unmodified lines101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046385 unmodified linesimport loggingimport osimport sysfrom pathlib import Pathimport requestsimport gradio as gr5 unmodified linestry:from .config import get_flask_urls, get_doctors_page_urls, TIMEOUT_SETTINGSexcept ImportError:def get_flask_urls():return ["http://127.0.0.1:600/complete_appointment",1 unmodified line"https://your-flask-app-domain.com/complete_appointment","http://your-flask-app-ip:600/complete_appointment"]def get_doctors_page_urls():return {"local": "http://127.0.0.1:600/doctors","production": "https://your-flask-app-domain.com/doctors"}TIMEOUT_SETTINGS = {"connection_timeout": 5, "request_timeout": 10}parent_dir = os.path.dirname(os.path.abspath(__file__))sys.path.append(parent_dir)logging.basicConfig(level=logging.INFO,format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",2 unmodified lineslogger = logging.getLogger(__name__)class MediSyncApp:def __init__(self):self.logger = logging.getLogger(__name__)self.logger.info("Initializing MediSync application")self._temp_files = []self.fusion_model = Noneself.image_model = Noneself.text_model = Nonedef __del__(self):self.cleanup_temp_files()def cleanup_temp_files(self):for temp_file in self._temp_files:try:if os.path.exists(temp_file):4 unmodified linesself._temp_files = []def load_models(self):if self.fusion_model is not None:return Truetry:self.logger.info("Loading models...")self.logger.info("Models loaded successfully (mock implementation)")return Trueexcept Exception as e:1 unmodified linereturn Falsedef enhance_image(self, image):if image is None:return Nonetry:enhanced_image = imageself.logger.info("Image enhanced successfully")return enhanced_image2 unmodified linesreturn imagedef analyze_image(self, image):if image is None:return None, "Please upload an image first.", Noneif not self.load_models():return image, "Error: Models not loaded properly.", Nonetry:self.logger.info("Analyzing image")results = {"primary_finding": "Normal chest X-ray","confidence": 0.85,4 unmodified lines("Cardiomegaly", 0.05)]}fig = self.plot_image_prediction(image,results.get("predictions", []),f"Primary Finding: {results.get('primary_finding', 'Unknown')}")plot_html = self.fig_to_html(fig)plt.close(fig)html_result = self.format_image_results(results)return image, html_result, plot_htmlexcept Exception as e:self.logger.error(f"Error in image analysis: {e}")return image, f"Error analyzing image: {str(e)}", Nonedef analyze_text(self, text):if not text or text.strip() == "":return "", "Please enter medical report text.", Noneif not self.load_models():return text, "Error: Models not loaded properly.", Nonetry:self.logger.info("Analyzing text")results = {"entities": [{"text": "chest X-ray", "type": "PROCEDURE", "confidence": 0.95},3 unmodified lines"sentiment": "neutral","key_findings": ["Normal heart size", "Clear lungs", "8mm nodular opacity"]}html_result = self.format_text_results(results)plot_html = self.create_entity_visualization(results["entities"])return text, html_result, plot_htmlexcept Exception as e:self.logger.error(f"Error in text analysis: {e}")return text, f"Error analyzing text: {str(e)}", Nonedef analyze_multimodal(self, image, text):if image is None and (not text or text.strip() == ""):return "Please provide either an image or text for analysis.", Noneif not self.load_models():return "Error: Models not loaded properly.", Nonetry:self.logger.info("Performing multimodal analysis")results = {"combined_finding": "Normal chest X-ray with minor findings","confidence": 0.92,4 unmodified lines"Monitor for any changes in symptoms"]}html_result = self.format_multimodal_results(results)plot_html = self.create_multimodal_visualization(results)return html_result, plot_htmlexcept Exception as e:self.logger.error(f"Error in multimodal analysis: {e}")return f"Error in multimodal analysis: {str(e)}", Nonedef format_image_results(self, results):html_result = f"""<div class="medisync-card medisync-card-bg medisync-force-text"><h2 class="medisync-title medisync-blue">X-ray Analysis Results</h2><p><strong>Primary Finding:</strong> {results.get("primary_finding", "Unknown")}</p><p><strong>Confidence:</strong> {results.get("confidence", 0):.1%}</p><p><strong>Abnormality Detected:</strong> {"Yes" if results.get("has_abnormality", False) else "No"}</p><h3>Top Predictions:</h3><ul>"""for label, prob in results.get("predictions", [])[:5]:html_result += f"<li>{label}: {prob:.1%}</li>"html_result += "</ul></div>"return html_resultdef format_text_results(self, results):html_result = f"""<div class="medisync-card medisync-card-bg medisync-force-text"><h2 class="medisync-title medisync-green">Text Analysis Results</h2><p><strong>Sentiment:</strong> {results.get("sentiment", "Unknown").title()}</p><h3>Key Findings:</h3><ul>"""for finding in results.get("key_findings", []):html_result += f"<li>{finding}</li>"html_result += "</ul>"html_result += "<h3>Extracted Entities:</h3><ul>"for entity in results.get("entities", [])[:5]:html_result += f"<li><strong>{entity['text']}</strong> ({entity['type']}) - {entity['confidence']:.1%}</li>"html_result += "</ul></div>"return html_resultdef format_multimodal_results(self, results):html_result = f"""<div class="medisync-card medisync-card-bg medisync-force-text"><h2 class="medisync-title medisync-purple">Multimodal Analysis Results</h2><p><strong>Combined Finding:</strong> {results.get("combined_finding", "Unknown")}</p><p><strong>Overall Confidence:</strong> {results.get("confidence", 0):.1%}</p><h3>Image Contribution:</h3><p>{results.get("image_contribution", "No image analysis available")}</p><h3>Text Contribution:</h3><p>{results.get("text_contribution", "No text analysis available")}</p><h3>Recommendations:</h3><ul>"""for rec in results.get("recommendations", []):html_result += f"<li>{rec}</li>"html_result += "</ul></div>"return html_resultdef plot_image_prediction(self, image, predictions, title):fig, ax = plt.subplots(figsize=(10, 6))ax.imshow(image)ax.set_title(title, fontsize=14, fontweight='bold', color='#007bff')ax.axis('off')return figdef create_entity_visualization(self, entities):if not entities:return "<p>No entities found in text.</p>"fig, ax = plt.subplots(figsize=(10, 6))entity_types = {}for entity in entities:entity_type = entity['type']if entity_type not in entity_types:entity_types[entity_type] = 0entity_types[entity_type] += 1if entity_types:ax.bar(entity_types.keys(), entity_types.values(), color='#00bfae')ax.set_title('Entity Types Found in Text', fontsize=14, fontweight='bold', color='#00bfae')ax.set_ylabel('Count', color='#00bfae')plt.xticks(rotation=45, color='#222')plt.yticks(color='#222')return self.fig_to_html(fig)def create_multimodal_visualization(self, results):fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6))confidence = results.get("confidence", 0)ax1.pie([confidence, 1-confidence], labels=['Confidence', 'Uncertainty'],colors=['#00bfae', '#ff7675'], autopct='%1.1f%%', textprops={'color': '#222'})ax1.set_title('Analysis Confidence', fontweight='bold', color='#00bfae')recommendations = results.get("recommendations", [])ax2.bar(['Recommendations'], [len(recommendations)], color='#6c63ff')ax2.set_title('Number of Recommendations', fontweight='bold', color='#6c63ff')ax2.set_ylabel('Count', color='#6c63ff')plt.tight_layout()return self.fig_to_html(fig)def fig_to_html(self, fig):import ioimport base64buf = io.BytesIO()fig.savefig(buf, format='png', bbox_inches='tight', dpi=100, facecolor=fig.get_facecolor())buf.seek(0)img_str = base64.b64encode(buf.read()).decode()buf.close()return f'<img src="data:image/png;base64,{img_str}" style="max-width: 100%; height: auto; background: transparent;"/>'def complete_appointment(appointment_id):try:flask_urls = get_flask_urls()payload = {"appointment_id": appointment_id}for flask_api_url in flask_urls:try:logger.info(f"Trying to connect to: {flask_api_url}")response = requests.post(flask_api_url, json=payload, timeout=TIMEOUT_SETTINGS["connection_timeout"])if response.status_code == 200:return {"status": "success", "message": "Appointment completed successfully"}elif response.status_code == 404:1 unmodified lineelse:logger.warning(f"Unexpected response from {flask_api_url}: {response.status_code}")continueexcept requests.exceptions.ConnectionError:logger.warning(f"Connection failed to {flask_api_url}")continue3 unmodified linesexcept Exception as e:logger.warning(f"Error with {flask_api_url}: {e}")continuereturn {"status": "error","message": "Cannot connect to Flask app. Please ensure the Flask app is running and accessible."}except Exception as e:logger.error(f"Error completing appointment: {e}")return {"status": "error", "message": f"Error: {str(e)}"}def create_interface():app = MediSyncApp()example_report = """CHEST X-RAY EXAMINATIONCLINICAL HISTORY: 55-year-old male with cough and fever.FINDINGS: The heart size is at the upper limits of normal. The lungs are clear without focal consolidation,effusion, or pneumothorax. There is mild prominence of the pulmonary vasculature. No pleural effusion is seen.There is a small nodular opacity noted in the right lower lobe measuring approximately 8mm, which is suspiciousand warrants further investigation. The mediastinum is unremarkable. The visualized bony structures show no acute abnormalities.IMPRESSION:1. Mild cardiomegaly.2. 8mm nodular opacity in the right lower lobe, recommend follow-up CT for further evaluation.3. No acute pulmonary parenchymal abnormality.RECOMMENDATIONS: Follow-up chest CT to further characterize the nodular opacity in the right lower lobe."""sample_images_dir = Path(parent_dir) / "data" / "sample"sample_images = list(sample_images_dir.glob("*.png")) + list(sample_images_dir.glob("*.jpg"))sample_image_path = str(sample_images[0]) if sample_images else Nonewith gr.Blocks(title="MediSync: Multi-Modal Medical Analysis System",theme=gr.themes.Default(), # Use Default for HuggingFace dark/light supportcss="""/* Modern neumorphic card style for all result containers */.medisync-card {border-radius: 18px;box-shadow: 0 4px 24px 0 rgba(0,0,0,0.10), 0 1.5px 4px 0 rgba(0,191,174,0.08);margin: 18px 0;padding: 24px 24px 18px 24px;font-size: 1.08rem;transition: background 0.2s, color 0.2s;}.medisync-card-bg {background: var(--background-fill-primary, #f8f9fa);color: var(--body-text-color, #222);}.medisync-title {font-weight: 700;margin-bottom: 0.7em;}.medisync-blue { color: #00bfae; }.medisync-green { color: #28a745; }.medisync-purple { color: #6c63ff; }.medisync-card ul, .medisync-card ol {margin-left: 1.2em;}.medisync-card li {margin-bottom: 0.2em;}/* Button and input styling for modern look */.gr-button, .end-consultation-btn {border-radius: 8px !important;font-weight: 600 !important;font-size: 1.08rem !important;transition: background 0.2s, color 0.2s;}.end-consultation-btn {background: linear-gradient(90deg, #dc3545 60%, #ff7675 100%) !important;border: none !important;color: #fff !important;box-shadow: 0 2px 8px 0 rgba(220,53,69,0.10);}.end-consultation-btn:hover {background: linear-gradient(90deg, #c82333 60%, #ff7675 100%) !important;}/* Responsive tweaks */@media (max-width: 900px) {.medisync-card { padding: 16px 8px 12px 8px; }}/* Ensure text is visible in dark mode */html[data-theme="dark"] .medisync-card-bg,html[data-theme="dark"] .medisync-card-bg.medisync-force-text {background: #23272f !important;color: #f8fafc !important;}html[data-theme="dark"] .medisync-title {color: #00bfae !important;}html[data-theme="dark"] .medisync-blue { color: #00bfae !important; }html[data-theme="dark"] .medisync-green { color: #00e676 !important; }html[data-theme="dark"] .medisync-purple { color: #a385ff !important; }/* Make sure all gradio labels and text are visible */label, .gr-label, .gr-text, .gr-html, .gr-markdown {color: var(--body-text-color, #222) !important;}html[data-theme="dark"] label, html[data-theme="dark"] .gr-label, html[data-theme="dark"] .gr-text, html[data-theme="dark"] .gr-html, html[data-theme="dark"] .gr-markdown {color: #f8fafc !important;}/* Force all text in medisync-card and status outputs to be visible in all themes */.medisync-force-text, .medisync-force-text * {color: var(--body-text-color, #222) !important;}html[data-theme="dark"] .medisync-force-text, html[data-theme="dark"] .medisync-force-text * {color: #f8fafc !important;}/* End consultation status output force text color */#end_consultation_status, #end_consultation_status * {color: var(--body-text-color, #222) !important;}html[data-theme="dark"] #end_consultation_status, html[data-theme="dark"] #end_consultation_status * {color: #f8fafc !important;}""") as interface:gr.Markdown("""<div style="display: flex; align-items: center; gap: 16px; margin-bottom: 0.5em;"><img src="https://cdn.jsdelivr.net/gh/saqib-ali-buriro/medivance-assets/medivance_logo.png" alt="Medivance Logo" style="height: 38px; border-radius: 8px; background: #fff; box-shadow: 0 2px 8px 0 rgba(26,115,232,0.10);"><span style="font-size: 2.1rem; font-weight: 700; color: #00bfae;">MediSync</span></div><div style="font-size: 1.18rem; margin-bottom: 1.2em;"><span style="color: var(--body-text-color, #222);">AI-powered Multi-Modal Medical Analysis System</span></div><div style="font-size: 1.05rem; margin-bottom: 1.2em;"><span style="color: var(--body-text-color, #222);">Seamlessly analyze X-ray images and medical reports for comprehensive healthcare insights.</span></div><div style="margin-bottom: 1.2em;"><ul style="font-size: 1.01rem; color: var(--body-text-color, #222);"><li>Upload a chest X-ray image</li><li>Enter the corresponding medical report text</li><li>Choose the analysis type: <b>Image</b>, <b>Text</b>, or <b>Multimodal</b></li><li>Click <b>End Consultation</b> to complete your appointment</li></ul></div>""",elem_id="medisync-header")with gr.Row():import urllib.parsetry:url_params = {}if hasattr(gr, 'get_current_url'):current_url = gr.get_current_url()if current_url:parsed = urllib.parse.urlparse(current_url)url_params = urllib.parse.parse_qs(parsed.query)default_appointment_id = url_params.get('appointment_id', [''])[0]except:default_appointment_id = ""appointment_id_input = gr.Textbox(label="Appointment ID",placeholder="Enter your appointment ID here...",info="This will be automatically populated if you came from the doctors page",value=default_appointment_id,elem_id="appointment_id_input")with gr.Tab("🧬 Multimodal Analysis"):with gr.Row():with gr.Column():multi_img_input = gr.Image(label="Upload X-ray Image", type="pil", elem_id="multi_img_input")multi_img_enhance = gr.Button("Enhance Image", icon="✨")multi_text_input = gr.Textbox(label="Enter Medical Report Text",placeholder="Enter the radiologist's report text here...",lines=10,value=example_report if sample_image_path is None else None,elem_id="multi_text_input")multi_analyze_btn = gr.Button("Analyze Image & Text", variant="primary", icon="🔎")with gr.Column():multi_results = gr.HTML(label="Analysis Results", elem_id="multi_results")multi_plot = gr.HTML(label="Visualization", elem_id="multi_plot")if sample_image_path:gr.Examples(examples=[[sample_image_path, example_report]],1 unmodified linelabel="Example X-ray and Report",)with gr.Tab("🖼️ Image Analysis"):with gr.Row():with gr.Column():img_input = gr.Image(label="Upload X-ray Image", type="pil", elem_id="img_input")img_enhance = gr.Button("Enhance Image", icon="✨")img_analyze_btn = gr.Button("Analyze Image", variant="primary", icon="🔎")with gr.Column():img_output = gr.Image(label="Processed Image", elem_id="img_output")img_results = gr.HTML(label="Analysis Results", elem_id="img_results")img_plot = gr.HTML(label="Visualization", elem_id="img_plot")if sample_image_path:gr.Examples(examples=[[sample_image_path]],1 unmodified linelabel="Example X-ray Image",)with gr.Tab("📝 Text Analysis"):with gr.Row():with gr.Column():text_input = gr.Textbox(1 unmodified lineplaceholder="Enter the radiologist's report text here...",lines=10,value=example_report,elem_id="text_input")text_analyze_btn = gr.Button("Analyze Text", variant="primary", icon="🔎")with gr.Column():text_output = gr.Textbox(label="Processed Text", elem_id="text_output")text_results = gr.HTML(label="Analysis Results", elem_id="text_results")text_plot = gr.HTML(label="Entity Visualization", elem_id="text_plot")gr.Examples(examples=[[example_report]],inputs=[text_input],label="Example Medical Report",)with gr.Row():with gr.Column():end_consultation_btn = gr.Button("End Consultation",variant="stop",size="lg",elem_classes=["end-consultation-btn"],icon="🛑")end_consultation_status = gr.HTML(label="Status", elem_id="end_consultation_status")with gr.Tab("ℹ️ About"):gr.Markdown("""<div class="medisync-card medisync-card-bg medisync-force-text"><h2 class="medisync-title medisync-blue">About MediSync</h2><p><b>MediSync</b> is an AI-powered healthcare solution that uses multi-modal analysis to provide comprehensive insights from medical images and reports.</p><h3>Key Features</h3><ul><li><b>X-ray Image Analysis</b>: Detects abnormalities in chest X-rays using pre-trained vision models</li><li><b>Medical Report Processing</b>: Extracts key information from patient reports using NLP models</li><li><b>Multi-modal Integration</b>: Combines insights from both image and text data for more accurate analysis</li></ul><h3>Models Used</h3><ul><li><b>X-ray Analysis</b>: facebook/deit-base-patch16-224-medical-cxr</li><li><b>Medical Text Analysis</b>: medicalai/ClinicalBERT</li></ul><h3 style="color:#dc3545;">Important Disclaimer</h3><p>This tool is for educational and research purposes only. It is not intended to provide medical advice or replace professional healthcare. Always consult with qualified healthcare providers for medical decisions.</p></div>""")# Event handlersmulti_img_enhance.click(app.enhance_image, inputs=multi_img_input, outputs=multi_img_input)2 unmodified linesinputs=[multi_img_input, multi_text_input],outputs=[multi_results, multi_plot],)img_enhance.click(app.enhance_image, inputs=img_input, outputs=img_output)img_analyze_btn.click(app.analyze_image,inputs=img_input,outputs=[img_output, img_results, img_plot],)text_analyze_btn.click(app.analyze_text,inputs=text_input,outputs=[text_output, text_results, text_plot],)def handle_end_consultation(appointment_id):if not appointment_id or appointment_id.strip() == "":return "<div class='medisync-force-text' style='color: #dc3545; padding: 10px; background-color: #ffe6e6; border-radius: 5px;'>Please enter your appointment ID first.</div>"result = complete_appointment(appointment_id.strip())if result["status"] == "success":doctors_urls = get_doctors_page_urls()html_response = f"""<div class='medisync-force-text' style='color: #28a745; padding: 15px; background-color: #e6ffe6; border-radius: 5px; margin: 10px 0;'><h3>✅ Consultation Completed Successfully!</h3><p>{result['message']}</p><p>Your appointment has been marked as completed.</p><button onclick="window.open('{doctors_urls['local']}', '_blank')"style="background-color: #00bfae; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; margin-top: 10px;">Return to Doctors Page (Local)</button><button onclick="window.open('{doctors_urls['production']}', '_blank')"style="background-color: #6c63ff; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; margin-top: 10px; margin-left: 10px;">Return to Doctors Page (Production)</button></div>"""else:if "Cannot connect to Flask app" in result['message']:html_response = f"""<div class='medisync-force-text' style='color: #ff9800; padding: 15px; background-color: #fff3cd; border-radius: 5px; margin: 10px 0;'><h3>⚠️ Consultation Ready to Complete</h3><p>Your consultation analysis is complete! However, we cannot automatically mark your appointment as completed because the Flask app is not accessible from this environment.</p><p><strong>Appointment ID:</strong> {appointment_id.strip()}</p>5 unmodified lines</ol><div style="margin-top: 15px;"><button onclick="window.open('http://127.0.0.1:600/complete_appointment_manual?appointment_id={appointment_id.strip()}', '_blank')"style="background-color: #00bfae; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; margin-right: 10px;">Complete Appointment</button><button onclick="window.open('http://127.0.0.1:600/doctors', '_blank')"style="background-color: #6c63ff; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; margin-right: 10px;">Return to Doctors Page</button><button onclick="navigator.clipboard.writeText('{appointment_id.strip()}')"style="background-color: #23272f; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer;">Copy Appointment ID</button></div>1 unmodified line"""else:html_response = f"""<div class='medisync-force-text' style='color: #dc3545; padding: 15px; background-color: #ffe6e6; border-radius: 5px; margin: 10px 0;'><h3>❌ Error Completing Consultation</h3><p>{result['message']}</p><p>Please try again or contact support if the problem persists.</p></div>"""return html_responseend_consultation_btn.click(2 unmodified linesoutputs=[end_consultation_status])# JavaScript for appointment ID auto-populationgr.HTML("""<script>function getUrlParameter(name) {name = name.replace(/[[]/, '\\[').replace(/[\]]/, '\\]');var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');var results = regex.exec(location.search);return results === null ? '' : decodeURIComponent(results[1].replace(/\\+/g, ' '));}function populateAppointmentId() {var appointmentId = getUrlParameter('appointment_id');if (appointmentId) {var input = document.getElementById('appointment_id_input');if (input) {input.value = appointmentId;var event = new Event('input', { bubbles: true });input.dispatchEvent(event);}}}document.addEventListener('DOMContentLoaded', function() {setTimeout(populateAppointmentId, 800);});window.addEventListener('load', function() {setTimeout(populateAppointmentId, 1200);});</script>""")interface.launch()if __name__ == "__main__":create_interface()
mediSync/app.py+207-416