Spaces:
Sleeping
Sleeping
Update app.py
Browse files239 unmodified lines24024124224324424524639 unmodified lines2862872882892882902912922912932942952962971 unmodified line2993003013023033043053063073083093103113123133143153163173183193203213223233243053253263273283293303311 unmodified line333334335313314315316317318319320336337338165 unmodified lines50450550650750849349449549649749849950050951051151251351451551651751851952052152252352452552652712 unmodified lines54054154251954354454554654754854955055121 unmodified lines57357457557655057757857958055458158258358458558658758858959059159259359459559659759815 unmodified lines6146156165825835845855865875885895905915926176186196204 unmodified lines6256266276036046056286296306311 unmodified line6336346356136146156366376386396406416426436186446456466476486496506516526536546256556566576583 unmodified lines6626636646356366376386396656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956416966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297306447316466476487327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847853 unmodified lines789790791658239 unmodified lines else: return "User info not found."
def get_chat_history(username): conn = sqlite3.connect("users.db") c = conn.cursor()39 unmodified lines pdf = FPDF() pdf.add_page() pdf.set_font("Arial", size=12) # Use safe_text to ensure the title is safe for latin-1 encoding pdf.cell(200, 10, txt="Patient Session Report", ln=True, align='C') pdf.cell(200, 10, txt=safe_text("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}") # Convert each line to a safe text version before writing it pdf.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 line pdf.output(filename) return filename
def safe_text(txt): # Encode the text to latin-1, replacing characters that can't be encoded return 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.value username = user_session.value conn = 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.value username = user_session.value 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,)) 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 line else: 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 lines
def handle_generate_report(): try: # Try to load session data and generate the PDF report. data = json.loads(session_data_state.value) except: return None pdf_file = generate_pdf_report(data) data["username"] = user_session.value data["appointment_date"] = "" data["pdf_report"] = pdf_file insert_patient_session(data) return pdf_file pdf_file = generate_pdf_report(data) data["username"] = user_session.value data["appointment_date"] = "" data["pdf_report"] = pdf_file insert_patient_session(data) return pdf_file except 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_filename
generate_report_btn.click(handle_generate_report, outputs=report_download)
12 unmodified lines def 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]) 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 lines if 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 strings datetime.strptime(appointment_date, "%Y-%m-%d") appointment_date_obj = 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") 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 object appointment_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 confirmation
book_button.click(book_appointment, inputs=[patient_name_appt, doctor_name, appointment_date, appointment_time, reason], outputs=booking_output)15 unmodified lines
search_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 = username prev_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 lines def 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 line back_to_login.click(back_to_login_page, outputs=[login_page, register_page])
# Toggle profile function def toggle_profile(user, current_visible): if not user: def toggle_profile(current_visible): #print("toggle_profile called with user:", user_session.value) # Debug print if not user_session.value: return gr.update(visible=False), False, "" new_visible = not current_visible info = get_user_info(user) if new_visible else "" info = 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=[user_session, profile_visible], inputs=[profile_visible], outputs=[profile_info_box, profile_visible, profile_info] )
3 unmodified lines if login_user(username, password): user_session.value = username prev_choices = get_previous_patients() return (f"Welcome, {username}!", gr.update(visible=True), # main_panel visible gr.update(visible=False), # login_page hidden gr.update(visible=True), # header_row visible gr.update(choices=prev_choices)) # update dropdown choices # Return 27 outputs now: existing 20 plus 7 more for sessions and booking tabs. return ( f"Welcome, {username}!", # login_output gr.update(visible=True), # main_panel gr.update(visible=False), # login_page gr.update(visible=True), # header_row gr.update(choices=prev_choices), # previous_patient "", # patient_name_input None, # age_input None, # gender_input "", # symptoms_input "", # diagnosis_textbox "", # diagnosis_conf_html "", # medication_textbox "", # medication_conf_html "", # therapy_textbox "", # therapy_conf_html "", # summary_textbox "", # explanation_textbox gr.update(visible=False), # generate_report_btn None, # 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: return "Invalid credentials.", gr.update(), gr.update(), gr.update(), gr.update() # On failure, clear those fields as well. return ( "Invalid credentials.", # login_output gr.update(), # main_panel gr.update(), # login_page gr.update(), # header_row gr.update(choices=prev_choices, value=None), # previous_patient (cleared) "", # patient_name_input None, # age_input None, # gender_input "", # symptoms_input "", # diagnosis_textbox "", # diagnosis_conf_html "", # medication_textbox "", # medication_conf_html "", # therapy_textbox "", # therapy_conf_html "", # summary_textbox "", # explanation_textbox gr.update(visible=False), # generate_report_btn None, # report_download "", # session_data_state "", # search_name "", # search_date "", # booking_output "", # patient_name_appt "", # appointment_date "", # appointment_time "" # reason )
# 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] 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_panel gr.update(visible=True), # Show login_page gr.update(visible=False), # Hide header_row gr.update(visible=False), # Hide profile_info_box False, # 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, email ] )
def main():3 unmodified linesif __name__ == "__main__": main()
app.py+185-52