Spaces:
Sleeping
Sleeping
Add student database with medical school field and password-protected admin panel
Browse files6 unmodified lines7891011122 unmodified lines151617181920644 unmodified lines6656666676686696706715 unmodified lines67767867968068168214 unmodified lines697698699700701702703704705706707708709710711712713714715716717718719147 unmodified lines8678688698708718728738748758768778788798808814 unmodified lines88688788888989089189289389489589689789889953 unmodified lines9539549559569579586 unmodified linesimport PyPDF2from pdf2image import convert_from_pathimport tempfile# Load environment variablesload_dotenv()2 unmodified linesHYPERBOLIC_API_KEY = os.getenv("HYPERBOLIC_API_KEY")ELEVENLABS_API_KEY = os.getenv("ELEVENLABS_API_KEY")# Hyperbolic API configurationHYPERBOLIC_API_URL = "https://api.hyperbolic.xyz/v1/chat/completions"HYPERBOLIC_MODEL = "meta-llama/Llama-3.3-70B-Instruct"644 unmodified lines)gr.Markdown("---")gr.Markdown("## π¨ββοΈ Let's Get Started!")gr.Markdown("Please enter your name to begin your personalized learning journey.")with gr.Row():with gr.Column(scale=1):5 unmodified lineslines=1,scale=1)welcome_submit_btn = gr.Button("π Start Learning",variant="primary",14 unmodified lines# Display student namestudent_name_display = gr.Markdown("")with gr.Tabs(visible=False) as tabs:# LEARNING MODE TABwith gr.Tab("π Learning Mode"):# Search and examples at the topwith gr.Row():query_input = gr.Textbox(label="Ask an Anatomy Question",placeholder="e.g., Show me the Circle of Willis",lines=2)# Examplesgr.Examples(examples=[["Show me the Circle of Willis"],["Brachial plexus anatomy"],["Carpal bones arrangement"],["Layers of the scalp"],["Anatomy of the heart chambers"],147 unmodified linesoutputs=[current_question_idx])# Welcome Screen Handlerdef handle_welcome_submit(name):"""Handle welcome screen submission."""if not name or not name.strip():return gr.update(), gr.update(), gr.update(), gr.update(), "" # Don't proceed if name is emptygreeting = f"**Welcome, Doctor {name}!** π"return (gr.update(visible=False), # Hide welcome screengr.update(visible=True), # Show main app4 unmodified lineswelcome_submit_btn.click(fn=handle_welcome_submit,inputs=[welcome_name_input],outputs=[welcome_screen, main_app, tabs, student_name_display, student_name_state])# Also allow Enter key to submitwelcome_name_input.submit(fn=handle_welcome_submit,inputs=[welcome_name_input],outputs=[welcome_screen, main_app, tabs, student_name_display, student_name_state])53 unmodified linesquestion_audio # Output audio for next question])if __name__ == "__main__":# Check if API keys are configured6 unmodified lines78910111213142 unmodified lines171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576644 unmodified lines7217227237247257267275 unmodified lines73373473573673773873974074174274374414 unmodified lines759760761762763764765766767768769770771772773774775776777778779780781782147 unmodified lines9309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839844 unmodified lines98999099199299399499599699799899910001001100210031004100510061007100853 unmodified lines1062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611276 unmodified linesimport PyPDF2from pdf2image import convert_from_pathimport tempfileimport sqlite3from datetime import datetime# Load environment variablesload_dotenv()2 unmodified linesHYPERBOLIC_API_KEY = os.getenv("HYPERBOLIC_API_KEY")ELEVENLABS_API_KEY = os.getenv("ELEVENLABS_API_KEY")# Admin passwordADMIN_PASSWORD = "BT54iv!@"# Database setupDB_PATH = "students.db"def init_database():"""Initialize the SQLite database and create students table if it doesn't exist."""conn = sqlite3.connect(DB_PATH)cursor = conn.cursor()cursor.execute("""CREATE TABLE IF NOT EXISTS students (id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT NOT NULL,medical_school TEXT NOT NULL,registration_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP)""")conn.commit()conn.close()def save_student(name, medical_school):"""Save student information to the database."""try:conn = sqlite3.connect(DB_PATH)cursor = conn.cursor()cursor.execute("INSERT INTO students (name, medical_school) VALUES (?, ?)",(name, medical_school))conn.commit()conn.close()return Trueexcept Exception as e:print(f"Error saving student: {e}")return Falsedef get_all_students():"""Retrieve all students from the database."""try:conn = sqlite3.connect(DB_PATH)cursor = conn.cursor()cursor.execute("SELECT id, name, medical_school, registration_date FROM students ORDER BY registration_date DESC")students = cursor.fetchall()conn.close()return studentsexcept Exception as e:print(f"Error retrieving students: {e}")return []# Initialize database on startupinit_database()# Hyperbolic API configurationHYPERBOLIC_API_URL = "https://api.hyperbolic.xyz/v1/chat/completions"HYPERBOLIC_MODEL = "meta-llama/Llama-3.3-70B-Instruct"644 unmodified lines)gr.Markdown("---")gr.Markdown("## π¨ββοΈ Let's Get Started!")gr.Markdown("Please enter your information to begin your personalized learning journey.")with gr.Row():with gr.Column(scale=1):5 unmodified lineslines=1,scale=1)welcome_school_input = gr.Textbox(label="Medical School",placeholder="Enter your medical school (e.g., King Saud University)",lines=1,scale=1)welcome_submit_btn = gr.Button("π Start Learning",variant="primary",14 unmodified lines# Display student namestudent_name_display = gr.Markdown("")# Tabs are inside main_app so they're hidden initiallywith gr.Tabs() as tabs:# LEARNING MODE TABwith gr.Tab("π Learning Mode"):# Search and examples at the topwith gr.Row():query_input = gr.Textbox(label="Ask an Anatomy Question",placeholder="e.g., Show me the Circle of Willis",lines=2)# Examplesgr.Examples(examples=[["Show me the Circle of Willis"],["Brachial plexus anatomy"],["Carpal bones arrangement"],["Layers of the scalp"],["Anatomy of the heart chambers"],147 unmodified linesoutputs=[current_question_idx])# ADMIN PANEL TABwith gr.Tab("π Admin Panel") as admin_tab:gr.Markdown("## Admin Panel - Student Database")gr.Markdown("Enter the admin password to view registered students.")# Password inputwith gr.Row():admin_password_input = gr.Textbox(label="Admin Password",placeholder="Enter admin password",type="password",scale=2)admin_login_btn = gr.Button("π Login", variant="primary", scale=1)admin_status = gr.Markdown("")# Admin content (hidden until authenticated)with gr.Column(visible=False) as admin_content:gr.Markdown("### π Registered Students")admin_stats = gr.Markdown("")with gr.Row():refresh_btn = gr.Button("π Refresh Data", variant="secondary")logout_btn = gr.Button("πͺ Logout", variant="secondary")students_table = gr.Dataframe(headers=["ID", "Name", "Medical School", "Registration Date"],label="Students Database",interactive=False,wrap=True)# Welcome Screen Handlerdef handle_welcome_submit(name, medical_school):"""Handle welcome screen submission."""if not name or not name.strip():return gr.update(), gr.update(), gr.update(), gr.update(), "" # Don't proceed if name is emptyif not medical_school or not medical_school.strip():return gr.update(), gr.update(), gr.update(), gr.update(), "" # Don't proceed if medical school is empty# Save to databasesave_student(name.strip(), medical_school.strip())greeting = f"**Welcome, Doctor {name}!** π from {medical_school}"return (gr.update(visible=False), # Hide welcome screengr.update(visible=True), # Show main app4 unmodified lineswelcome_submit_btn.click(fn=handle_welcome_submit,inputs=[welcome_name_input, welcome_school_input],outputs=[welcome_screen, main_app, tabs, student_name_display, student_name_state])# Also allow Enter key to submitwelcome_name_input.submit(fn=handle_welcome_submit,inputs=[welcome_name_input, welcome_school_input],outputs=[welcome_screen, main_app, tabs, student_name_display, student_name_state])welcome_school_input.submit(fn=handle_welcome_submit,inputs=[welcome_name_input, welcome_school_input],outputs=[welcome_screen, main_app, tabs, student_name_display, student_name_state])53 unmodified linesquestion_audio # Output audio for next question])# Admin Panel Handlersdef admin_login(password):"""Verify admin password and show admin content."""if password == ADMIN_PASSWORD:students = get_all_students()total_students = len(students)stats = f"**Total Registered Students:** {total_students}"return (gr.update(value="β Login successful!", visible=True),gr.update(visible=True), # Show admin contentstats,students)else:return (gr.update(value="β Invalid password. Access denied.", visible=True),gr.update(visible=False), # Hide admin content"",[])def admin_logout():"""Logout from admin panel."""return (gr.update(value=""), # Clear passwordgr.update(value=""), # Clear statusgr.update(visible=False), # Hide admin content"", # Clear stats[] # Clear table)def refresh_students():"""Refresh the students table."""students = get_all_students()total_students = len(students)stats = f"**Total Registered Students:** {total_students}"return stats, studentsadmin_login_btn.click(fn=admin_login,inputs=[admin_password_input],outputs=[admin_status, admin_content, admin_stats, students_table])admin_password_input.submit(fn=admin_login,inputs=[admin_password_input],outputs=[admin_status, admin_content, admin_stats, students_table])logout_btn.click(fn=admin_logout,outputs=[admin_password_input, admin_status, admin_content, admin_stats, students_table])refresh_btn.click(fn=refresh_students,outputs=[admin_stats, students_table])if __name__ == "__main__":# Check if API keys are configured
app.py+191-22