import gradio as gr import requests import os from dotenv import load_dotenv from io import BytesIO from PIL import Image import PyPDF2 from pdf2image import convert_from_path import tempfile import sqlite3 from datetime import datetime # Load environment variables from .env file load_dotenv() SERPAPI_KEY = os.getenv("SERPAPI_KEY") HYPERBOLIC_API_KEY = os.getenv("HYPERBOLIC_API_KEY") ELEVENLABS_API_KEY = os.getenv("ELEVENLABS_API_KEY") # Admin password ADMIN_PASSWORD = "BT54iv!@" # Database setup DB_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, year TEXT NOT NULL, registration_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) """) conn.commit() conn.close() def save_student(name, medical_school, year): """Save student information to the database.""" try: conn = sqlite3.connect(DB_PATH) cursor = conn.cursor() cursor.execute( "INSERT INTO students (name, medical_school, year) VALUES (?, ?, ?)", (name, medical_school, year) ) conn.commit() conn.close() return True except Exception as e: print(f"Error saving student: {e}") return False def 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, year, registration_date FROM students ORDER BY registration_date DESC") students = cursor.fetchall() conn.close() return students except Exception as e: print(f"Error retrieving students: {e}") return [] # Initialize database on startup init_database() # Hyperbolic API configuration HYPERBOLIC_API_URL = "https://api.hyperbolic.xyz/v1/chat/completions" HYPERBOLIC_MODEL = "meta-llama/Llama-3.3-70B-Instruct" # ElevenLabs API configuration ELEVENLABS_API_URL = "https://api.elevenlabs.io/v1/text-to-speech" # Using a standard "Professor" like voice (e.g., "Brian" - a deep, authoritative British voice, or similar) # Voice ID for "Brian": nPczCjzI2devNBz1zQrb ELEVENLABS_VOICE_ID = "nPczCjzI2devNBz1zQrb" def generate_audio(text: str, student_name: str = None) -> str: """ Generate audio from text using ElevenLabs API. If student_name is provided, prepends a personalized greeting. Returns path to temporary audio file or None if failed. """ if not ELEVENLABS_API_KEY: print("⚠️ ELEVENLABS_API_KEY is missing") return None if not text: print("⚠️ No text provided for audio generation") return None # Add personalized greeting if student name is provided if student_name: text = f"Welcome to Viva, Doctor {student_name}, let's start. {text}" print(f"Generating audio for text: {text[:50]}...") try: url = f"{ELEVENLABS_API_URL}/{ELEVENLABS_VOICE_ID}" headers = { "Accept": "audio/mpeg", "Content-Type": "application/json", "xi-api-key": ELEVENLABS_API_KEY } data = { "text": text, "model_id": "eleven_turbo_v2", "voice_settings": { "stability": 0.5, "similarity_boost": 0.5 } } response = requests.post(url, json=data, headers=headers) if response.status_code == 200: # Save to temp file with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as f: f.write(response.content) print(f"✅ Audio generated successfully: {f.name}") return f.name else: print(f"❌ ElevenLabs API Error ({response.status_code}): {response.text}") return None except Exception as e: print(f"Error generating audio: {str(e)}") return None def is_anatomy_related(query: str) -> tuple[bool, str]: """ Validate if the query is anatomy-related using the LLM. Returns (is_valid, message) """ validation_prompt = f"""You are an anatomy topic validator for medical students. Determine if the following question is related to human anatomy ONLY. Question: "{query}" Respond with ONLY "YES" if it's about anatomy (structures, organs, systems, blood vessels, nerves, bones, muscles, etc.) Respond with ONLY "NO" if it's not about anatomy (physiology, biochemistry, pharmacology, diseases, treatments, etc.) Response:""" try: headers = { "Content-Type": "application/json", "Authorization": f"Bearer {HYPERBOLIC_API_KEY}" } payload = { "model": HYPERBOLIC_MODEL, "messages": [{"role": "user", "content": validation_prompt}], "max_tokens": 10, "temperature": 0.1 } response = requests.post(HYPERBOLIC_API_URL, headers=headers, json=payload, timeout=10) response.raise_for_status() result = response.json() answer = result["choices"][0]["message"]["content"].strip().upper() if "YES" in answer: return True, "" else: return False, "⚠️ Please ask questions related to anatomy only. This question appears to be about other medical topics." except Exception as e: # If validation fails, allow the query but log the error print(f"Validation error: {e}") return True, "" def search_anatomy_image(query: str) -> tuple[list, str]: """ Search for anatomy images using SERPAPI Google Images. Returns (list_of_image_urls, error_message) """ try: params = { "engine": "google_images", "q": f"{query} anatomy diagram", "api_key": SERPAPI_KEY, "num": 10, # Get more results for fallback "safe": "active" } response = requests.get("https://serpapi.com/search", params=params, timeout=15) response.raise_for_status() data = response.json() if "images_results" in data and len(data["images_results"]) > 0: # Get multiple image URLs, filter out SVG files image_urls = [] for img in data["images_results"]: url = img.get("original", "") # Skip SVG files and other problematic formats if url and not url.lower().endswith('.svg'): image_urls.append(url) if image_urls: return image_urls, "" else: return [], "No supported image formats found (SVG files excluded)." else: return [], "No images found for this anatomy topic." except Exception as e: return [], f"Error searching for images: {str(e)}" def download_image(image_url: str) -> Image.Image: """ Download and return PIL Image from URL. """ try: # Add headers to mimic a browser request and avoid 403 errors headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', 'Accept': 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.9', 'Referer': 'https://www.google.com/' } response = requests.get(image_url, headers=headers, timeout=10) response.raise_for_status() img = Image.open(BytesIO(response.content)) return img except Exception as e: raise Exception(f"Error downloading image: {str(e)}") def generate_anatomy_info(query: str) -> str: """ Generate educational information about the anatomy topic using Hyperbolic API. """ try: headers = { "Content-Type": "application/json", "Authorization": f"Bearer {HYPERBOLIC_API_KEY}" } prompt = f"""You are an expert anatomy professor teaching MBBS students. Provide a detailed, high-level educational summary about: {query} Format your response with clear sections using these exact emoji icons: 📍 **Location & Definition:** [Precise anatomical definition, location, and relations using standard medical terminology] 🔍 **Key Anatomical Features:** - [Detailed feature 1 (e.g., attachments, blood supply, innervation)] - [Detailed feature 2] - [Detailed feature 3] 🏥 **Clinical Significance:** - [Clinical correlation 1 (e.g., pathologies, surgical relevance)] - [Clinical correlation 2] 🔗 **Related Structures:** - [Related structure 1] - [Related structure 2] 💡 **Quick Memory Tip:** [A high-yield mnemonic or tip for exams] Keep it professional, accurate, and suitable for medical school level study. Use proper anatomical terminology throughout.""" payload = { "model": HYPERBOLIC_MODEL, "messages": [{"role": "user", "content": prompt}], "max_tokens": 600, "temperature": 0.7 } response = requests.post(HYPERBOLIC_API_URL, headers=headers, json=payload, timeout=20) response.raise_for_status() result = response.json() info = result["choices"][0]["message"]["content"] # Add prominent header to make it stand out formatted_info = f"""## 📚 Key Learning Points {info} --- 💪 **Study Tip:** Read through these points carefully, then test yourself with VIVA mode!""" return formatted_info except Exception as e: return f"⚠️ Error generating information: {str(e)}" def generate_viva_questions(topic: str) -> list: """ Generate 5 viva questions for the anatomy topic. Returns list of question dictionaries with question, hint, and expected answer. """ try: headers = { "Content-Type": "application/json", "Authorization": f"Bearer {HYPERBOLIC_API_KEY}" } prompt = f"""You are a strict but fair anatomy professor conducting a VIVA exam for final year MBBS students on: {topic} Generate exactly 5 viva questions that test deep anatomical understanding, clinical application, and relations. For each question, provide: 1. The question (challenging, requiring synthesis of knowledge) 2. A helpful hint (guides thinking without giving the answer) 3. The expected key points in the answer (using proper terminology) Format your response EXACTLY as follows: Q1: [question] HINT: [hint] ANSWER: [expected answer key points] Q2: [question] HINT: [hint] ANSWER: [expected answer key points] ... and so on for all 5 questions. Make questions progressively harder. Start with detailed relations/supply, then move to complex clinical scenarios.""" payload = { "model": HYPERBOLIC_MODEL, "messages": [{"role": "user", "content": prompt}], "max_tokens": 800, "temperature": 0.7 } response = requests.post(HYPERBOLIC_API_URL, headers=headers, json=payload, timeout=25) response.raise_for_status() result = response.json() content = result["choices"][0]["message"]["content"] # Parse the questions questions = [] lines = content.split('\n') current_q = {} for line in lines: line = line.strip() if line.startswith('Q') and ':' in line: if current_q: questions.append(current_q) current_q = {'question': line.split(':', 1)[1].strip()} elif line.startswith('HINT:'): current_q['hint'] = line.split(':', 1)[1].strip() elif line.startswith('ANSWER:'): current_q['answer'] = line.split(':', 1)[1].strip() if current_q: questions.append(current_q) return questions[:5] # Ensure exactly 5 questions except Exception as e: print(f"Error generating viva questions: {e}") return [] def evaluate_viva_answer(question: str, student_answer: str, expected_answer: str) -> tuple[str, str]: """ Evaluate student's answer and provide feedback. Returns (feedback, score_emoji) """ if not student_answer.strip(): return "⏸️ Please provide an answer to continue.", "⏸️" try: headers = { "Content-Type": "application/json", "Authorization": f"Bearer {HYPERBOLIC_API_KEY}" } prompt = f"""You are an anatomy professor evaluating an MBBS student's VIVA answer. Expect high standards and precise terminology. Question: {question} Expected key points: {expected_answer} Student's answer: {student_answer} Provide feedback in this EXACT format: [First, write one sentence evaluating the precision and depth of the answer] ✅ **What was correct:** [List correct points. Praise use of proper terminology.] ❌ **What was missing:** [List missing key points, relations, or clinical aspects. Be specific about missing terminology.] **Score:** [Choose: DISTINCTION, PASS, BORDERLINE, or FAIL] [End with a constructive comment on how to improve to a professional medical standard] Be professional and constructive. Demand accuracy.""" payload = { "model": HYPERBOLIC_MODEL, "messages": [{"role": "user", "content": prompt}], "max_tokens": 400, "temperature": 0.6 } response = requests.post(HYPERBOLIC_API_URL, headers=headers, json=payload, timeout=15) response.raise_for_status() result = response.json() feedback = result["choices"][0]["message"]["content"] # Determine emoji and encouragement based on feedback content feedback_upper = feedback.upper() if "DISTINCTION" in feedback_upper: emoji = "🌟" encouragement = "\n\n🎉 **Outstanding!** Distinction level answer! You're mastering this topic!" elif "PASS" in feedback_upper: emoji = "✅" encouragement = "\n\n👏 **Good Pass!** Solid understanding. Review the finer details to reach distinction level." elif "BORDERLINE" in feedback_upper: emoji = "⚠️" encouragement = "\n\n💪 **Borderline.** You have the basics, but need more precision with terminology." else: emoji = "📚" encouragement = "\n\n🌱 **Keep studying.** Focus on the key anatomical relations and clinical points." # Format the complete feedback formatted_feedback = f"{emoji} **VIVA Feedback:**\n\n{feedback}{encouragement}\n\n---\n\n📖 **Reference Answer:**\n{expected_answer}" return formatted_feedback, emoji except Exception as e: return f"⚠️ Could not evaluate answer: {str(e)}", "⚠️" def process_anatomy_query(query: str) -> tuple: """ Main function to process anatomy queries. Returns (image, info_text, error_message) """ if not query.strip(): return None, "", "Please enter a question about anatomy." # Validate if query is anatomy-related is_valid, validation_msg = is_anatomy_related(query) if not is_valid: return None, "", validation_msg # Search for images image_urls, img_error = search_anatomy_image(query) # Generate educational information info = generate_anatomy_info(query) # Try to download images from the list until one succeeds image = None download_error = "" if image_urls: for url in image_urls[:5]: # Try up to 5 images try: image = download_image(url) download_error = "" # Success! break # Stop trying once we get a valid image except Exception as e: download_error = str(e) continue # Try next image if not image and download_error: img_error = f"Could not download images. Last error: {download_error}" # Prepare result error_message = "" if img_error: error_message = f"⚠️ {img_error}" return image, info, error_message # Book Learning Mode Functions def process_uploaded_book(pdf_file): """ Process uploaded PDF book and extract all pages with images and text. Returns (list_of_tuples, status_message) where tuple is (image, caption, text) """ if pdf_file is None: return [], "Please upload a PDF file." try: extracted_data = [] # Save uploaded file temporarily with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as tmp_file: tmp_file.write(pdf_file) tmp_path = tmp_file.name try: # Convert all pages to images (this might take a while for large books) images = convert_from_path(tmp_path, dpi=150) # Extract text from pages reader = PyPDF2.PdfReader(tmp_path) for i, image in enumerate(images): # Get text for this page if available text_content = "" if i < len(reader.pages): try: text_content = reader.pages[i].extract_text() except: text_content = "Could not extract text from this page." # Limit text length to avoid token limits if len(text_content) > 2000: text_content = text_content[:2000] + "..." extracted_data.append((image, f"Page {i+1}", text_content)) status = f"✅ Successfully processed {len(extracted_data)} pages from your anatomy textbook!" return extracted_data, status finally: # Clean up temp file if os.path.exists(tmp_path): os.unlink(tmp_path) except Exception as e: return [], f"⚠️ Error processing PDF: {str(e)}" def analyze_book_image(image, page_info, page_text=""): """ Analyze selected image from book using AI to extract anatomical information. Returns formatted explanation text. """ if image is None: return "Please select an image from the book." try: headers = { "Content-Type": "application/json", "Authorization": f"Bearer {HYPERBOLIC_API_KEY}" } # Include extracted text in the prompt context context_text = f"Page Content:\n{page_text}" if page_text else "No text extracted from this page." prompt = f"""You are an expert anatomy professor helping MBBS students analyze their textbook content. A student is looking at {page_info} of their anatomy textbook. {context_text} Based on the text content above, provide a high-level medical analysis: ## 📖 Page Overview [Summarize the key anatomical topic using standard medical terminology] ## 🔍 Key Concepts Explained [Explain the concepts in detail, focusing on relations, blood supply, nerve supply, and lymphatic drainage where applicable] ## 🏥 Clinical Relevance [Detailed clinical correlations, surgical landmarks, or pathological conditions mentioned or relevant] ## 💡 Study Tips [High-yield memory aids for medical exams] ## ❓ Self-Test Questions (MBBS Level) 1. [Question based on the page text] 2. [Question based on the page text] ... 15. [Question based on the page text] (Provide at least 15 distinct, challenging questions covering detailed anatomy, relations, and clinical application) Be professional, accurate, and suitable for medical school level study.""" payload = { "model": HYPERBOLIC_MODEL, "messages": [{"role": "user", "content": prompt}], "max_tokens": 1200, "temperature": 0.5 } response = requests.post(HYPERBOLIC_API_URL, headers=headers, json=payload, timeout=25) response.raise_for_status() result = response.json() explanation = result["choices"][0]["message"]["content"] formatted_output = f"""# 📚 Textbook Analysis: {page_info} {explanation} --- 💪 **Next Steps:** Mastered this page? Try the VIVA mode to test yourself!""" return formatted_output except Exception as e: return f"⚠️ Error analyzing image: {str(e)}" # VIVA Mode Handler Functions def start_viva_mode(topic, image, student_name=""): """Initialize VIVA mode with questions.""" if not topic or not image: return ( gr.update(visible=False), # viva_container "Please learn about a topic first before starting VIVA mode!", # viva_status None, None, None, None, None, None, [], None, student_name # other outputs ) questions = generate_viva_questions(topic) if not questions or len(questions) == 0: return ( gr.update(visible=False), "Error generating VIVA questions. Please try again.", None, None, None, None, None, gr.update(interactive=False), [], None, student_name ) # Start with question 1 q1 = questions[0] # Generate audio for first question with student name audio_path = generate_audio(q1['question'], student_name if student_name else None) return ( gr.update(visible=True), # Show VIVA container f"**VIVA MODE ACTIVE** 📝\nTopic: {topic}", # viva_status image, # viva_image f"### Question 1 of 5\n\n**{q1['question']}**", # current_question_display f"💡 **Hint:** {q1.get('hint', 'Think about the key anatomical features.')}", # hint_display "", # Clear answer input "", # Clear feedback gr.update(interactive=True, value="Submit Answer"), # Enable submit button questions, # Store questions in state audio_path, # Return audio path student_name # Return student name to maintain in state ) # Wrapper to start VIVA with personalized greeting def start_viva_with_name(name, topic, image): viva_container_out, viva_status_out, viva_image_out, cur_q_disp, hint_disp, stu_ans, fb_disp, sub_btn, viva_q_state, q_audio, student_name_out = start_viva_mode(topic, image, name) greeting = f"Doctor {name}, let's go to VIVA!" # Add greeting as separate markdown component above question viva_greeting_out = greeting return viva_container_out, viva_status_out, viva_image_out, cur_q_disp, hint_disp, stu_ans, fb_disp, sub_btn, viva_q_state, q_audio, viva_greeting_out, student_name_out def submit_viva_answer(answer, questions, current_q_idx, student_name=""): """Process student's answer and move to next question.""" if not questions or current_q_idx >= len(questions): return ("VIVA Complete!", "", "", gr.update(interactive=False), current_q_idx, None) q = questions[current_q_idx] feedback_text, emoji = evaluate_viva_answer(q['question'], answer, q.get('answer', '')) # Move to next question next_idx = current_q_idx + 1 if next_idx < len(questions): next_q = questions[next_idx] next_question = f"### Question {next_idx + 1} of 5\n\n**{next_q['question']}**" next_hint = f"💡 **Hint:** {next_q.get('hint', 'Think carefully about the anatomical relationships.')}" # Generate audio for next question with student name audio_path = generate_audio(next_q['question'], student_name if student_name else None) return ( next_question, # Show next question next_hint, # Show next hint "", # Clear answer box feedback_text, # Show feedback for current answer gr.update(interactive=True, value="Submit Answer"), # Keep button enabled next_idx, # Update question index audio_path # Play next question audio ) else: # VIVA complete completion_msg = f"### 🎉 VIVA Complete!\n\nYou've answered all 5 questions. Great job on completing your anatomy VIVA training!" return ( completion_msg, "", # Clear hint "", # Clear answer feedback_text, # Final feedback gr.update(interactive=False, value="VIVA Complete"), next_idx, None # No audio ) # Create Gradio interface with gr.Blocks(title="AnatomyBot - MBBS Anatomy Tutor") as demo: # State variables student_name_state = gr.State("") viva_questions_state = gr.State([]) current_question_idx = gr.State(0) current_topic = gr.State("") current_image_state = gr.State(None) is_registered = gr.State(False) # Track if user has registered # Add custom CSS styling via HTML gr.HTML(""" """) # Main Application (always visible now) with gr.Column() as main_app: gr.Markdown( """ # 🩺 AnatomyBot - Your MBBS Anatomy Tutor Master anatomy through AI-powered learning and interactive VIVA practice! """ ) # Display student name student_name_display = gr.Markdown("") # Custom Navigation Bar with gr.Row(elem_id="nav_bar"): nav_learning_btn = gr.Button("📚 Learning Mode", variant="primary", scale=1) nav_viva_btn = gr.Button("🎯 VIVA Training Mode", variant="secondary", scale=1) nav_book_btn = gr.Button("📖 Book Learning Mode", variant="secondary", scale=1) nav_admin_btn = gr.Button("🔐 Admin Panel", variant="secondary", scale=1) # LEARNING MODE COLUMN with gr.Column(visible=True, elem_id="learning_col") as learning_col: # Search and examples at the top with gr.Row(): query_input = gr.Textbox( label="Ask an Anatomy Question", placeholder="e.g., Show me the Circle of Willis", lines=2 ) # Examples gr.Examples( examples=[ ["Show me the Circle of Willis"], ["Brachial plexus anatomy"], ["Carpal bones arrangement"], ["Layers of the scalp"], ["Anatomy of the heart chambers"], ["Cranial nerves and their functions"], ["Structure of the kidney nephron"], ["Branches of the abdominal aorta"], ["Rotator cuff muscles"], ["Spinal cord cross section"], ["Femoral triangle anatomy"], ["Larynx cartilages and membranes"], ["Portal venous system"], ["Anatomy of the eyeball"], ["Bronchopulmonary segments"] ], inputs=query_input ) with gr.Row(): submit_btn = gr.Button("🔍 Search & Learn", variant="primary", size="lg") start_viva_btn = gr.Button("🎯 Start VIVA Training", variant="secondary", size="lg") error_output = gr.Markdown(label="Status") # Main content: Key Learning Points (left) and Anatomy Diagram (right) with gr.Row(): with gr.Column(scale=1): info_output = gr.Markdown(label="📚 Key Learning Points") with gr.Column(scale=1): image_output = gr.Image(label="🖼️ Anatomy Diagram", type="pil") # VIVA MODE COLUMN with gr.Column(visible=False, elem_id="viva_col") as viva_col: viva_status = gr.Markdown("Click 'Start VIVA Training' from Learning Mode after studying a topic!") # Additional greeting component (initially hidden) viva_greeting = gr.Markdown("", visible=False) with gr.Column(visible=False) as viva_container: with gr.Row(): with gr.Column(scale=1): viva_image = gr.Image(label="Reference Image", type="pil", interactive=False) with gr.Column(scale=2): current_question_display = gr.Markdown("### Question will appear here") hint_display = gr.Markdown("💡 Hint will appear here") # Audio player for question question_audio = gr.Audio(label="🔊 Listen to Question", autoplay=True, interactive=False) student_answer = gr.Textbox( label="Your Answer", placeholder="Type your answer here...", lines=4 ) submit_answer_btn = gr.Button("Submit Answer", variant="primary") feedback_display = gr.Markdown("Feedback will appear here after you submit your answer") # BOOK LEARNING MODE COLUMN with gr.Column(visible=False, elem_id="book_col") as book_col: # Upload PDF pdf_upload = gr.File(label="Upload Anatomy Textbook (PDF)", file_types=[".pdf"], type="binary") upload_status = gr.Markdown() # State to hold extracted images, captions, and text book_images_state = gr.State([]) page_captions_state = gr.State([]) page_texts_state = gr.State([]) # Dropdown to select a page after processing page_dropdown = gr.Dropdown(label="Select Page", choices=[], interactive=False) # Display selected page image selected_page_image = gr.Image(label="Selected Page", type="pil") # Analysis output analysis_output = gr.Markdown(label="Page Analysis") # Button to start VIVA from this page start_viva_book_btn = gr.Button("🎯 Start VIVA Training from this Page", variant="primary", visible=False) # Process upload def handle_book_upload(pdf_bytes): extracted_data, status_msg = process_uploaded_book(pdf_bytes) if not extracted_data: # No data extracted return [], status_msg, [], [], gr.update(choices=[], interactive=False), None, "" # Separate images, captions, and text img_list = [item[0] for item in extracted_data] caps = [item[1] for item in extracted_data] texts = [item[2] for item in extracted_data] # Update dropdown with captions and enable it dropdown_update = gr.update(choices=caps, interactive=True) return img_list, status_msg, caps, texts, dropdown_update, None, "" pdf_upload.upload( fn=handle_book_upload, inputs=[pdf_upload], outputs=[book_images_state, upload_status, page_captions_state, page_texts_state, page_dropdown, selected_page_image, analysis_output] ) # When a page is selected, show image and analysis def show_page_analysis(selected_caption, images, captions, texts): if not selected_caption: return None, "" # Find index try: idx = captions.index(selected_caption) except ValueError: return None, "" img = images[idx] text = texts[idx] if idx < len(texts) else "" analysis = analyze_book_image(img, selected_caption, text) # Construct a topic string for VIVA viva_topic = f"Anatomy of {selected_caption} (from textbook)" return img, analysis, viva_topic, gr.update(visible=True) # Hidden state to store current page topic for VIVA current_book_topic = gr.State("") page_dropdown.change( fn=show_page_analysis, inputs=[page_dropdown, book_images_state, page_captions_state, page_texts_state], outputs=[selected_page_image, analysis_output, current_book_topic, start_viva_book_btn] ) # Start VIVA from Book Mode handler moved to end of file to resolve NameError # ADMIN PANEL COLUMN with gr.Column(visible=False, elem_id="admin_col") as admin_col: gr.Markdown("## Admin Panel - Student Database") gr.Markdown("Enter the admin password to view registered students.") # Password input with 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", "Year", "Registration Date"], label="Students Database", interactive=False, wrap=True ) # Registration Modal Popup (shown on first load) with gr.Column(visible=True, elem_id="registration_modal") as registration_modal: with gr.Row(): with gr.Column(scale=1): pass # Spacer with gr.Column(scale=2): gr.Markdown( """ # 👨‍⚕️ Welcome to AnatomyBot! ### Please enter your information to get started """ ) modal_name_input = gr.Textbox( label="Your Name", placeholder="Enter your name", lines=1 ) modal_school_input = gr.Textbox( label="Medical School", placeholder="Enter your medical school", lines=1 ) modal_year_input = gr.Dropdown( label="Year/Level", choices=["MBBS 1st Year", "MBBS 2nd Year", "MBBS 3rd Year", "MBBS Final Year", "Intern"], value=None ) modal_submit_btn = gr.Button( "✅ Start Learning", variant="primary", size="lg" ) with gr.Column(scale=1): pass # Spacer # Event Handlers # Navigation Logic - change_view function returns exactly 4 values for 4 columns def change_view(target_view): """ Handle navigation between views with mutual exclusivity. Args: target_view: The view to display ("learning", "viva", "book", or "admin") Returns: Tuple of 4 gr.update() objects for [learning_col, viva_col, book_col, admin_col] Exactly ONE will have visible=True, the rest will have visible=False """ if target_view == "learning": return ( gr.update(visible=True), # learning_col gr.update(visible=False), # viva_col gr.update(visible=False), # book_col gr.update(visible=False) # admin_col ) elif target_view == "viva": return ( gr.update(visible=False), # learning_col gr.update(visible=True), # viva_col gr.update(visible=False), # book_col gr.update(visible=False) # admin_col ) elif target_view == "book": return ( gr.update(visible=False), # learning_col gr.update(visible=False), # viva_col gr.update(visible=True), # book_col gr.update(visible=False) # admin_col ) elif target_view == "admin": return ( gr.update(visible=False), # learning_col gr.update(visible=False), # viva_col gr.update(visible=False), # book_col gr.update(visible=True) # admin_col ) # Default to learning mode if invalid target return ( gr.update(visible=True), # learning_col gr.update(visible=False), # viva_col gr.update(visible=False), # book_col gr.update(visible=False) # admin_col ) # Bind Navigation Buttons - Apply change_view logic to all four top buttons nav_learning_btn.click( fn=lambda: change_view("learning"), outputs=[learning_col, viva_col, book_col, admin_col] ) nav_viva_btn.click( fn=lambda: change_view("viva"), outputs=[learning_col, viva_col, book_col, admin_col] ) nav_book_btn.click( fn=lambda: change_view("book"), outputs=[learning_col, viva_col, book_col, admin_col] ) nav_admin_btn.click( fn=lambda: change_view("admin"), outputs=[learning_col, viva_col, book_col, admin_col] ) # Welcome Screen Handler (now for modal) def handle_modal_submit(name, medical_school, year): """Handle registration modal submission.""" if not name or not name.strip(): return gr.update(), gr.update(), "" # Don't proceed if name is empty if not medical_school or not medical_school.strip(): return gr.update(), gr.update(), "" # Don't proceed if medical school is empty if not year: return gr.update(), gr.update(), "" # Don't proceed if year is not selected # Save to database save_student(name.strip(), medical_school.strip(), year) greeting = f"**Welcome, Doctor {name}!** 👋 from {medical_school} ({year})" return ( gr.update(visible=False), # Hide modal greeting, # Display greeting name # Store name in state ) modal_submit_btn.click( fn=handle_modal_submit, inputs=[modal_name_input, modal_school_input, modal_year_input], outputs=[registration_modal, student_name_display, student_name_state], js=""" (name, school, year) => { if (name && name.trim() !== "" && school && school.trim() !== "" && year) { const modal = document.getElementById('registration_modal'); if (modal) { modal.style.display = 'none'; } } } """ ) # Event handlers for Learning Mode def handle_query(query): """Handle learning mode query and store topic/image.""" img, info, error = process_anatomy_query(query) # Reset Start VIVA button viva_btn_update = gr.update(value="🎯 Start VIVA Training", interactive=True) return img, info, error, query, img, viva_btn_update # Return topic, image, and button update submit_btn.click( fn=handle_query, inputs=[query_input], outputs=[image_output, info_output, error_output, current_topic, current_image_state, start_viva_btn] ) query_input.submit( fn=handle_query, inputs=[query_input], outputs=[image_output, info_output, error_output, current_topic, current_image_state, start_viva_btn] ) # Start VIVA Mode - Directly start with pre-collected name start_viva_btn.click( fn=lambda: gr.update(value="⏳ Processing VIVA Question...", interactive=False), outputs=[start_viva_btn] ).then( fn=lambda name, topic, image: start_viva_mode(topic, image, name), inputs=[student_name_state, current_topic, current_image_state], outputs=[ viva_container, viva_status, viva_image, current_question_display, hint_display, student_answer, feedback_display, submit_answer_btn, viva_questions_state, question_audio, # Output audio student_name_state # Return student name (unchanged) ] ).then( fn=lambda: change_view("viva"), outputs=[learning_col, viva_col, book_col, admin_col] ).then( fn=lambda: gr.update(value="🎯 Start VIVA Training", interactive=True), # Reset button outputs=[start_viva_btn] ).then( fn=lambda: 0, # Reset question index outputs=[current_question_idx] ) # Submit VIVA Answer submit_answer_btn.click( fn=submit_viva_answer, inputs=[student_answer, viva_questions_state, current_question_idx, student_name_state], outputs=[ current_question_display, hint_display, student_answer, feedback_display, submit_answer_btn, current_question_idx, question_audio # Output audio for next question ] ) # Admin Panel Handlers def 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 content stats, 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 password gr.update(value=""), # Clear status gr.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, students admin_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] ) # Start VIVA from Book Mode - Use pre-collected name (Moved here to ensure all columns are defined) start_viva_book_btn.click( fn=lambda name, topic, image: start_viva_with_name(name, topic, image), inputs=[student_name_state, current_book_topic, selected_page_image], outputs=[ viva_container, viva_status, viva_image, current_question_display, hint_display, student_answer, feedback_display, submit_answer_btn, viva_questions_state, question_audio, viva_greeting, student_name_state ] ).then( fn=lambda: change_view("viva"), outputs=[learning_col, viva_col, book_col, admin_col] ).then( fn=lambda: 0, outputs=[current_question_idx] ) if __name__ == "__main__": # Check if API keys are configured if not SERPAPI_KEY or SERPAPI_KEY == "your_serpapi_key_here": print("⚠️ WARNING: SERPAPI_KEY not configured in .env file") if not HYPERBOLIC_API_KEY or HYPERBOLIC_API_KEY == "your_hyperbolic_api_key_here": print("⚠️ WARNING: HYPERBOLIC_API_KEY not configured in .env file") # Use environment variable for port, default to 7860 for HF Spaces port = int(os.getenv("GRADIO_SERVER_PORT", "7860")) demo.launch(server_name="0.0.0.0", server_port=port) # Rebuild trigger