Spaces:
Runtime error
Runtime error
updated code ✅✅
Browse files466 unmodified lines4674684694704714724734744754764774784794804814824834844854864874883 unmodified lines492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645466 unmodified linescss=custom_css) as interface:# Appointment ID handling - simplified approachappointment_id = gr.Textbox(visible=False)# Initialize appointment ID from URL using Gradio's built-in methoddef get_appointment_id():try:from gradio.context import Contextif hasattr(Context, 'request') and hasattr(Context.request, 'query_params'):return Context.request.query_params.get("appointment_id", "")except Exception as e:logger.warning(f"Could not get URL parameters: {str(e)}")return ""interface.load(fn=get_appointment_id,outputs=[appointment_id])gr.Markdown("""3 unmodified linesto provide comprehensive medical insights.""")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 not sample_image_path 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")if sample_image_path:gr.Examples(examples=[[sample_image_path, example_report]],inputs=[multi_img_input, multi_text_input],label="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")if sample_image_path:gr.Examples(examples=[[sample_image_path]],inputs=[img_input],label="Example X-ray Image",)with gr.Tab("Text Analysis"):with gr.Row():with gr.Column():text_input = gr.Textbox(label="Enter Medical Report Text",placeholder="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")gr.Examples(examples=[[example_report]],inputs=[text_input],label="Example Medical Report",)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.""")with gr.Row():with gr.Column():end_consultation_btn = gr.Button("End Consultation", variant="stop", size="lg")completion_status = gr.HTML()# Event handlersmulti_img_enhance.click(app.enhance_image, inputs=multi_img_input, outputs=multi_img_input)multi_analyze_btn.click(app.analyze_multimodal,inputs=[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 complete_consultation(appointment_id):if not appointment_id:error_html = """<div class="alert-box alert-error"><strong>No Appointment ID Found</strong><p>Your session may not be properly recorded.</p></div>"""logger.error("Completion attempted without appointment ID")return error_htmltry:response = requests.post("http://127.0.0.1:600/complete_consultation",json={"appointment_id": appointment_id},timeout=10)if response.ok:success_html = """<div class="alert-box alert-success"><strong>Consultation Completed</strong><p>You will be redirected shortly.</p><script>setTimeout(() => window.location.href = "http://127.0.0.1:600/doctors", 2000);</script></div>"""logger.info(f"Successfully completed appointment {appointment_id}")return success_htmlerror_msg = f"Server error: {response.status_code}"if response.text:error_msg += f" - {response.text[:200]}"logger.error(error_msg)return f"""<div class="alert-box alert-error"><strong>Error Completing Appointment</strong><p>{error_msg}</p></div>"""except Exception as e:logger.error(f"Completion error: {str(e)}")return f"""<div class="alert-box alert-error"><strong>Connection Error</strong><p>{str(e)}</p></div>"""end_consultation_btn.click(fn=complete_consultation,inputs=[appointment_id],outputs=[completion_status])try:interface.launch()except Exception as e:466 unmodified lines4674684694704714724734744754764774784794804814824834844854864874884894904914924933 unmodified lines497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583466 unmodified linescss=custom_css) as interface:# Session state to track if consultation was properly recordedsession_state = gr.State({'recorded': False,'appointment_id': ''})# Initialize appointment ID from URLdef get_appointment_id():try:from gradio.context import Contextif hasattr(Context, 'request') and hasattr(Context.request, 'query_params'):appointment_id = Context.request.query_params.get("appointment_id", "")if appointment_id:return {'recorded': False, 'appointment_id': appointment_id}except Exception as e:logger.warning(f"Could not get URL parameters: {str(e)}")return {'recorded': False, 'appointment_id': ''}interface.load(fn=get_appointment_id,outputs=[session_state])gr.Markdown("""3 unmodified linesto provide comprehensive medical insights.""")# ... (keep all your existing tabs and components)with gr.Row():with gr.Column():end_consultation_btn = gr.Button("End Consultation", variant="stop", size="lg")completion_status = gr.HTML()def complete_consultation(session_state):"""Handle consultation completion with proper session recording."""if not session_state['appointment_id']:error_html = """<div class="alert-box alert-error"><strong>No Appointment ID Found</strong><p>Please contact support to ensure your session is recorded.</p></div>"""logger.error("Completion attempted without appointment ID")return {'recorded': False, 'appointment_id': ''}, error_htmltry:# First verify if already recordedif session_state['recorded']:success_html = """<div class="alert-box alert-success"><strong>Consultation Already Completed</strong><p>You will be redirected shortly.</p><script>setTimeout(() => window.location.href = "http://127.0.0.1:600/doctors", 1000);</script></div>"""return session_state, success_html# Call your Flask endpoint to record completionresponse = requests.post("http://127.0.0.1:600/complete_consultation",json={"appointment_id": session_state['appointment_id']},timeout=10)if response.ok:success_html = """<div class="alert-box alert-success"><strong>Consultation Successfully Recorded</strong><p>Your session has been properly recorded.</p><p>You will be redirected shortly.</p><script>setTimeout(() => window.location.href = "http://127.0.0.1:600/doctors", 2000);</script></div>"""logger.info(f"Successfully recorded appointment {session_state['appointment_id']}")return {'recorded': True, 'appointment_id': session_state['appointment_id']}, success_htmlerror_msg = f"Server error: {response.status_code}"if response.text:error_msg += f" - {response.text[:200]}"logger.error(error_msg)return session_state, f"""<div class="alert-box alert-error"><strong>Recording Failed</strong><p>{error_msg}</p><p>Please try again or contact support.</p></div>"""except Exception as e:logger.error(f"Completion error: {str(e)}")return session_state, f"""<div class="alert-box alert-error"><strong>Connection Error</strong><p>{str(e)}</p><p>Please check your connection and try again.</p></div>"""end_consultation_btn.click(fn=complete_consultation,inputs=[session_state],outputs=[session_state, completion_status])try:interface.launch()except Exception as e:
mediSync/app.py+47-109