Spaces:
Runtime error
Runtime error
updated code , for new feature✅✅
Browse files384 unmodified lines38538638738838939042 unmodified lines43343443543643743843944066 unmodified lines50750850951051151239 unmodified lines552553554555556557558559560561562563384 unmodified linesreturn "<p>Error displaying visualization.</p>"def create_interface():"""Create and launch the Gradio interface."""42 unmodified lines1. Upload a chest X-ray image2. Enter the corresponding medical report text3. Choose the analysis type: image-only, text-only, or multimodal (combined)""")with gr.Tab("Multimodal Analysis"):with gr.Row():with gr.Column():66 unmodified lineslabel="Example Medical Report",)with gr.Tab("About"):gr.Markdown("""## About MediSync39 unmodified linesoutputs=[text_output, text_results, text_plot],)# Run the interfaceinterface.launch()if __name__ == "__main__":create_interface()# Example Script384 unmodified lines38538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676742 unmodified lines81081181281381481581681781881982082182282382482582682766 unmodified lines89489589689789889990090190290390490590690790890991039 unmodified lines950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050384 unmodified linesreturn "<p>Error displaying visualization.</p>"import loggingimport osimport sysimport tempfilefrom pathlib import Pathimport requestsimport gradio as grimport matplotlib.pyplot as pltfrom PIL import Imageimport json# 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",handlers=[logging.StreamHandler(), logging.FileHandler("mediSync.log")],)logger = 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):os.remove(temp_file)self.logger.debug(f"Cleaned up temporary file: {temp_file}")except Exception as e:self.logger.warning(f"Failed to clean up temporary file {temp_file}: {e}")self._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:self.logger.error(f"Error loading models: {e}")return 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_imageexcept Exception as e:self.logger.error(f"Error enhancing image: {e}")return 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,"has_abnormality": False,"predictions": [("Normal", 0.85),("Pneumonia", 0.10),("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},{"text": "55-year-old male", "type": "PATIENT", "confidence": 0.90},{"text": "cough and fever", "type": "SYMPTOM", "confidence": 0.88}],"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,"image_contribution": "Normal cardiac silhouette and clear lung fields","text_contribution": "Clinical history supports normal findings","recommendations": ["Follow-up CT for the 8mm nodular opacity","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:# Call the Flask API to complete the appointmentflask_api_url = "http://127.0.0.1:600/complete_appointment"payload = {"appointment_id": appointment_id}response = requests.post(flask_api_url, json=payload, timeout=10)if response.status_code == 200:return {"status": "success", "message": "Appointment completed successfully"}else:return {"status": "error", "message": f"Failed to complete appointment: {response.text}"}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."""42 unmodified lines1. 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 inputwith gr.Row():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=gr.State("") # This will be populated via JavaScript)with gr.Tab("Multimodal Analysis"):with gr.Row():with gr.Column():66 unmodified lineslabel="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 MediSync39 unmodified linesoutputs=[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>"result = complete_appointment(appointment_id.strip())if result["status"] == "success":# 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('http://127.0.0.1:600/doctors', '_blank')"style="background-color: #007bff; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; margin-top: 10px;">Return to Doctors Page</button></div>"""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(handle_end_consultation,inputs=[appointment_id_input],outputs=[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');if (appointmentId) {// Find the appointment ID input field and populate itvar inputs = document.querySelectorAll('input[type="text"]');for (var i = 0; i < inputs.length; i++) {if (inputs[i].placeholder && inputs[i].placeholder.includes('appointment ID')) {inputs[i].value = appointmentId;break;}}}}// Run when page loadsdocument.addEventListener('DOMContentLoaded', function() {populateAppointmentId();});// Also run after Gradio loads (in case of dynamic loading)if (typeof gradio !== 'undefined') {gradio.addEventListener('load', function() {setTimeout(populateAppointmentId, 1000);});}</script>""")# Run the interfaceinterface.launch()if __name__ == "__main__":create_interface()# Example Script
mediSync/app.py+489-2