Spaces:
Sleeping
Sleeping
Update app.py
Browse files239 unmodified lines24024124224324424524639 unmodified lines2862872882892902912922932942952962971 unmodified line2993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303311 unmodified line333334335336337338165 unmodified lines50450550650750850951051151251351451551651751851952052152252352452552652712 unmodified lines54054154254354454554654754854955055121 unmodified lines57357457557657757857958058158258358458558658758858959059159259359459559659759815 unmodified lines6146156166176186196204 unmodified lines6256266276286296306311 unmodified line6336346356366376386396406416426436446456466476486496506516526536546556566576583 unmodified lines6626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847853 unmodified lines789790791239 unmodified lineselse:return "User info not found."def get_chat_history(username):conn = sqlite3.connect("users.db")c = conn.cursor()39 unmodified linespdf = FPDF()pdf.add_page()pdf.set_font("Arial", size=12)# Use safe_text to ensure the title is safe for latin-1 encodingpdf.cell(200, 10, txt=safe_text("Patient Session Report"), ln=True, align='C')pdf.ln(10)for key, value in session_data.items():# Convert each line to a safe text version before writing itpdf.multi_cell(0, 10, txt=safe_text(f"{key.capitalize()}: {value}"))reports_dir = "reports"os.makedirs(reports_dir, exist_ok=True)timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")1 unmodified linepdf.output(filename)return filenamedef safe_text(txt):# Encode the text to latin-1, replacing characters that can't be encodedreturn txt.encode("latin-1", "replace").decode("latin-1")# --------------------------# Helper: Autofill Previous Patient Info# --------------------------def get_previous_patients():# Use the current logged-in user from user_session.valueusername = user_session.valueconn = sqlite3.connect("users.db")c = conn.cursor()c.execute("SELECT DISTINCT patient_name FROM patient_sessions WHERE username=?", (username,))records = c.fetchall()conn.close()return [r[0] for r in records]def get_previous_patient_info(selected_patient):# Use the current logged-in user from user_session.valueusername = user_session.valueconn = sqlite3.connect("users.db")c = conn.cursor()c.execute("SELECT patient_name, age, gender FROM patient_sessions WHERE username=? AND patient_name=? ORDER BY session_timestamp DESC LIMIT 1",(username, selected_patient))record = c.fetchone()conn.close()if record:1 unmodified lineelse:return "", None, ""# --------------------------# Gradio UI Setup with External CSS# --------------------------165 unmodified linesdef handle_generate_report():try:# Try to load session data and generate the PDF report.data = json.loads(session_data_state.value)pdf_file = generate_pdf_report(data)data["username"] = user_session.valuedata["appointment_date"] = ""data["pdf_report"] = pdf_fileinsert_patient_session(data)return pdf_fileexcept Exception as e:# Create an error file that contains the error message.error_msg = f"Error generating PDF report: {str(e)}"reports_dir = "reports"os.makedirs(reports_dir, exist_ok=True)error_filename = f"{reports_dir}/error_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"with open(error_filename, "w", encoding="utf-8") as f:f.write(error_msg)return error_filenamegenerate_report_btn.click(handle_generate_report, outputs=report_download)12 unmodified linesdef load_history():if user_session.value:history = get_chat_history(user_session.value)chat_history_text = "\n".join([f"[{h[2]}] {h[0]}\nBot: {h[1]}" for h in history])return f"Username: {user_session.value}\n\n{chat_history_text}"else:return "Please log in to view history."load_history_btn.click(load_history, outputs=history_output)with gr.Tab("Book an Appointment"):21 unmodified linesif not re.fullmatch(r"[A-Za-z ]+", patient_name):return "Patient name should contain only letters and spaces."try:# Parse the appointment date and time stringsappointment_date_obj = datetime.strptime(appointment_date, "%Y-%m-%d")except ValueError:return "Appointment date must be in YYYY-MM-DD format."try:appointment_time_obj = datetime.strptime(appointment_time, "%H:%M")except ValueError:return "Appointment time must be in HH:MM (24-hour) format."# Combine date and time into a single datetime objectappointment_datetime = datetime.combine(appointment_date_obj.date(), appointment_time_obj.time())now = datetime.now()if appointment_datetime <= now:return "Appointment date/time has already passed. Please select a future date and time."confirmation = (f"Appointment booked for {patient_name} with {doctor_name} on {appointment_date} at {appointment_time}.\n\n"f"Reason: {reason}")return confirmationbook_button.click(book_appointment,inputs=[patient_name_appt, doctor_name, appointment_date, appointment_time, reason],outputs=booking_output)15 unmodified linessearch_button.click(search_sessions, inputs=[search_name, search_date], outputs=sessions_output)def handle_register(username, password, full_name, email):return register_user(username, password, full_name, email)4 unmodified linesdef back_to_login_page():return gr.update(visible=True), gr.update(visible=False)go_to_register.click(go_to_register_page, outputs=[login_page, register_page])register_btn.click(handle_register,inputs=[new_username, new_password, full_name, email],1 unmodified lineback_to_login.click(back_to_login_page, outputs=[login_page, register_page])def toggle_profile(current_visible):#print("toggle_profile called with user:", user_session.value) # Debug printif not user_session.value:return gr.update(visible=False), False, ""new_visible = not current_visibleinfo = get_user_info(user_session.value) if new_visible else ""return gr.update(visible=new_visible), new_visible, info# Connect profile button click with correct input order:profile_button.click(toggle_profile,inputs=[profile_visible],outputs=[profile_info_box, profile_visible, profile_info])3 unmodified linesif login_user(username, password):user_session.value = usernameprev_choices = get_previous_patients()# Return 27 outputs now: existing 20 plus 7 more for sessions and booking tabs.return (f"Welcome, {username}!", # login_outputgr.update(visible=True), # main_panelgr.update(visible=False), # login_pagegr.update(visible=True), # header_rowgr.update(choices=prev_choices), # previous_patient"", # patient_name_inputNone, # age_inputNone, # gender_input"", # symptoms_input"", # diagnosis_textbox"", # diagnosis_conf_html"", # medication_textbox"", # medication_conf_html"", # therapy_textbox"", # therapy_conf_html"", # summary_textbox"", # explanation_textboxgr.update(visible=False), # generate_report_btnNone, # report_download"", # session_data_state"", # search_name (Patient Sessions tab)"", # search_date (Patient Sessions tab)"", # booking_output (Book an Appointment tab)"", # patient_name_appt (Booking tab field)"", # appointment_date (Booking tab field)"", # appointment_time (Booking tab field)"" # reason (Booking tab field))else:# On failure, clear those fields as well.return ("Invalid credentials.", # login_outputgr.update(), # main_panelgr.update(), # login_pagegr.update(), # header_rowgr.update(choices=prev_choices, value=None), # previous_patient (cleared)"", # patient_name_inputNone, # age_inputNone, # gender_input"", # symptoms_input"", # diagnosis_textbox"", # diagnosis_conf_html"", # medication_textbox"", # medication_conf_html"", # therapy_textbox"", # therapy_conf_html"", # summary_textbox"", # explanation_textboxgr.update(visible=False), # generate_report_btnNone, # report_download"", # session_data_state"", # search_name"", # search_date"", # booking_output"", # patient_name_appt"", # appointment_date"", # appointment_time"" # reason)login_btn.click(handle_login,inputs=[username_login, password_login],outputs=[login_output, main_panel, login_page, header_row, previous_patient,patient_name_input, age_input, gender_input, symptoms_input,diagnosis_textbox, diagnosis_conf_html,medication_textbox, medication_conf_html,therapy_textbox, therapy_conf_html,summary_textbox, explanation_textbox,generate_report_btn, report_download, session_data_state,search_name, search_date, booking_output, patient_name_appt, appointment_date, appointment_time, reason])def handle_logout():user_session.value = ""return (gr.update(visible=False), # Hide main_panelgr.update(visible=True), # Show login_pagegr.update(visible=False), # Hide header_rowgr.update(visible=False), # Hide profile_info_boxFalse, # Reset profile_visible"", # Clear profile_info"", # Clear login_output"", # Clear history_output"", # Clear username_login textbox"", # Clear password_login textbox"", # Clear new_username textbox (register page)"", # Clear new_password textbox (register page)"", # Clear full_name textbox (register page)"" # Clear email textbox (register page))logout_button.click(handle_logout,outputs=[main_panel,login_page,header_row,profile_info_box,profile_visible,profile_info,login_output,history_output,username_login,password_login,new_username,new_password,full_name,])def main():3 unmodified linesif __name__ == "__main__":main()239 unmodified lines24024124224324424539 unmodified lines2852862872882892902912922932941 unmodified line2962972982993003013023033043053063073081 unmodified line310311312313314315316317318319320321322323165 unmodified lines48949049149249349449549649749849950050150250312 unmodified lines51651751851952052152252352452521 unmodified lines54754854955055155255355455555655755855956056156256315 unmodified lines5795805815825835845855865875885895905915925935945954 unmodified lines6006016026036046056066076081 unmodified line6106116126136146156166176186196206216226236246256266276283 unmodified lines6326336346356366376386396406416426436446456466476486496506513 unmodified lines655656657658239 unmodified lineselse:return "User info not found."def get_chat_history(username):conn = sqlite3.connect("users.db")c = conn.cursor()39 unmodified linespdf = FPDF()pdf.add_page()pdf.set_font("Arial", size=12)pdf.cell(200, 10, txt="Patient Session Report", ln=True, align='C')pdf.ln(10)for key, value in session_data.items():pdf.multi_cell(0, 10, txt=f"{key.capitalize()}: {value}")reports_dir = "reports"os.makedirs(reports_dir, exist_ok=True)timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")1 unmodified linepdf.output(filename)return filename# --------------------------# Helper: Autofill Previous Patient Info# --------------------------def get_previous_patient_info(selected_patient):conn = sqlite3.connect("users.db")c = conn.cursor()c.execute("SELECT patient_name, age, gender FROM patient_sessions WHERE patient_name=? ORDER BY session_timestamp DESC LIMIT 1", (selected_patient,))record = c.fetchone()conn.close()if record:1 unmodified lineelse:return "", None, ""def get_previous_patients():conn = sqlite3.connect("users.db")c = conn.cursor()c.execute("SELECT DISTINCT patient_name FROM patient_sessions")records = c.fetchall()conn.close()return [r[0] for r in records]# --------------------------# Gradio UI Setup with External CSS# --------------------------165 unmodified linesdef handle_generate_report():try:data = json.loads(session_data_state.value)except:return Nonepdf_file = generate_pdf_report(data)data["username"] = user_session.valuedata["appointment_date"] = ""data["pdf_report"] = pdf_fileinsert_patient_session(data)return pdf_filegenerate_report_btn.click(handle_generate_report, outputs=report_download)12 unmodified linesdef load_history():if user_session.value:history = get_chat_history(user_session.value)return "\n".join([f"[{h[2]}] {h[0]}\nBot: {h[1]}" for h in history])else:return "Please log in to view history."load_history_btn.click(load_history, outputs=history_output)with gr.Tab("Book an Appointment"):21 unmodified linesif not re.fullmatch(r"[A-Za-z ]+", patient_name):return "Patient name should contain only letters and spaces."try:datetime.strptime(appointment_date, "%Y-%m-%d")except ValueError:return "Appointment date must be in YYYY-MM-DD format."try:datetime.strptime(appointment_time, "%H:%M")except ValueError:return "Appointment time must be in HH:MM (24-hour) format."confirmation = (f"Appointment booked for {patient_name} with {doctor_name} on {appointment_date} at {appointment_time}.\n\n"f"Reason: {reason}")return confirmationbook_button.click(book_appointment,inputs=[patient_name_appt, doctor_name, appointment_date, appointment_time, reason],outputs=booking_output)15 unmodified linessearch_button.click(search_sessions, inputs=[search_name, search_date], outputs=sessions_output)def handle_login(username, password):if login_user(username, password):user_session.value = usernameprev_choices = get_previous_patients()return (f"Welcome, {username}!",gr.update(visible=True),gr.update(visible=False),gr.update(visible=True),gr.update(choices=prev_choices))else:return "Invalid credentials.", gr.update(), gr.update(), gr.update(), gr.update()def handle_register(username, password, full_name, email):return register_user(username, password, full_name, email)4 unmodified linesdef back_to_login_page():return gr.update(visible=True), gr.update(visible=False)login_btn.click(handle_login,inputs=[username_login, password_login],outputs=[login_output, main_panel, login_page, header_row])go_to_register.click(go_to_register_page, outputs=[login_page, register_page])register_btn.click(handle_register,inputs=[new_username, new_password, full_name, email],1 unmodified lineback_to_login.click(back_to_login_page, outputs=[login_page, register_page])# Toggle profile functiondef toggle_profile(user, current_visible):if not user:return gr.update(visible=False), False, ""new_visible = not current_visibleinfo = get_user_info(user) if new_visible else ""return gr.update(visible=new_visible), new_visible, info# Connect profile button click with correct input order:profile_button.click(toggle_profile,inputs=[user_session, profile_visible],outputs=[profile_info_box, profile_visible, profile_info])3 unmodified linesif login_user(username, password):user_session.value = usernameprev_choices = get_previous_patients()return (f"Welcome, {username}!",gr.update(visible=True), # main_panel visiblegr.update(visible=False), # login_page hiddengr.update(visible=True), # header_row visiblegr.update(choices=prev_choices)) # update dropdown choiceselse:return "Invalid credentials.", gr.update(), gr.update(), gr.update(), gr.update()# Connect login button click:login_btn.click(handle_login,inputs=[username_login, password_login],outputs=[login_output, main_panel, login_page, header_row, previous_patient])def main():3 unmodified linesif __name__ == "__main__":main()
app.py+52-185