Spaces:
Runtime error
Runtime error
updated the code script ✅✅
Browse files395 unmodified lines396397398399400401345 unmodified lines74774874975075175275375475575675775875976076176250 unmodified lines813814815816817818819820821822823824825132 unmodified lines95895996096196296396496596696796896997097197241 unmodified lines101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110422 unmodified lines104510461047104810491050395 unmodified linesfrom PIL import Imageimport json# Add parent directory to pathparent_dir = os.path.dirname(os.path.abspath(__file__))sys.path.append(parent_dir)345 unmodified linesdict: 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}")50 unmodified lines4. 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"):132 unmodified linesresult = 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>"""41 unmodified lines// 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>""")2 unmodified linesif __name__ == "__main__":create_interface()# Example Script395 unmodified lines396397398399400401402403404405406407408409410411412413414415416417418419420421422345 unmodified lines76876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580650 unmodified lines857858859860861862863864865866867868869870871872873874875876877878879880881882883884132 unmodified lines101710181019102010211022102310241025102610271028102910301031103210331034103510361037103841 unmodified lines10801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511762 unmodified lines1179118011811182395 unmodified linesfrom PIL import Imageimport json# Import configurationtry: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","http://localhost:600/complete_appointment","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)345 unmodified linesdict: 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:return {"status": "error", "message": "Appointment not found"}else: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}")continueexcept requests.exceptions.Timeout:logger.warning(f"Timeout connecting to {flask_api_url}")continueexcept 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}")50 unmodified lines4. 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"):132 unmodified linesresult = 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>"""41 unmodified lines// Function to populate appointment ID from URLfunction populateAppointmentId() {var appointmentId = getUrlParameter('appointment_id');console.log('Found appointment ID:', appointmentId);if (appointmentId) {// Try multiple selectors to find the appointment ID inputvar 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:', element);element.value = appointmentId;// Trigger change eventvar event = new Event('input', { bubbles: true });element.dispatchEvent(event);console.log('Set appointment ID to:', appointmentId);return true;}}// If not found by placeholder, try by labelvar 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);return true;}}}console.log('Could not find appointment ID input field');} else {console.log('No appointment ID found in URL');}return false;}// 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>""")2 unmodified linesif __name__ == "__main__":create_interface()
mediSync/app.py+158-26