import gradio as gr import json import os import random import google.generativeai as genai # Function to get available JSON files in the working directory def get_available_weeks(): files = [f for f in os.listdir() if f.startswith('week-') and f.endswith('.json')] return files # Function to load questions from the specified week file def load_questions(week_file): try: with open(week_file, "r") as f: data = json.load(f) return data, None except FileNotFoundError: return None, f"File {week_file} not found." # Flashcard UI function def flashcard_ui(week_file, index): data, error = load_questions(week_file) if error: return f"Error: {error}", None question = data[index]["question"] total = len(data) return f"Question {index + 1}/{total}: {question}", "" # Reveal answer function def reveal_answer(week_file, index): data, error = load_questions(week_file) if error: return None answer = data[index]["answer"] return answer # Function to handle navigation def change_question(week_file, index, direction): data, _ = load_questions(week_file) total = len(data) index = (index + direction) % total return index, *flashcard_ui(week_file, index) # Function to load mock test questions def load_mocktest(): try: with open("mocktest.json", "r") as f: data = json.load(f) return data except FileNotFoundError: return None def display_mock_question(index, score, incorrect_questions): data = load_mocktest() if not data: return "Mocktest file not found.", None, None, None, None, None question_data = data[index] question = f"Question {index + 1}: {question_data['question']}" correct_answer = question_data["correct-answer"] all_answers = question_data["wrong-answers"] + [correct_answer] random.shuffle(all_answers) return question, all_answers[0], all_answers[1], all_answers[2], all_answers[3], correct_answer def handle_answer(answer, mock_index, score, incorrect_questions): data = load_mocktest() correct_answer = data[mock_index]["correct-answer"] current_question = data[mock_index]["question"] if answer == correct_answer: score += 1 else: incorrect_questions.append((current_question, correct_answer)) mock_index += 1 if mock_index >= len(data): result = generate_test_result(score, len(data), incorrect_questions) return gr.update(value=result), gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), mock_index, score, incorrect_questions return gr.update(), gr.update(visible=False), gr.update(), gr.update(), gr.update(), gr.update(), mock_index, score, incorrect_questions def generate_test_result(score, total_questions, incorrect_questions): percentage = (score / total_questions) * 100 result = f"Your score: {score}/{total_questions} ({percentage:.2f}%)\n\n" if incorrect_questions: result += "Incorrect Questions and Correct Answers:\n\n" for i, (question, answer) in enumerate(incorrect_questions, 1): result += f"{i}. Question: {question}\n Correct Answer: {answer}\n\n" else: result += "Congratulations! You answered all questions correctly." return result def restart_test(): return 0, 0, [], gr.update(value=""), gr.update(value="", visible=True), gr.update(value="", visible=True), gr.update(value="", visible=True), gr.update(value="", visible=True), gr.update(value="", visible=False), gr.update(visible=False) def update_question(mock_index, score, incorrect_questions): data = load_mocktest() if mock_index >= len(data): result = generate_test_result(score, len(data), incorrect_questions) return gr.update(value=result), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False) question, ans1, ans2, ans3, ans4, correct = display_mock_question(mock_index, score, incorrect_questions) return gr.update(value=question), gr.update(value=ans1, visible=True), gr.update(value=ans2, visible=True), gr.update(value=ans3, visible=True), gr.update(value=ans4, visible=True) with open("aa2.txt", "r") as f: prompt = f.read() genai.configure(api_key=os.environ["GEMINI_API_KEY"]) # Create the model configuration generation_config = { "temperature": 0.5, "top_p": 0.98, "top_k": 64, "max_output_tokens": 8192, "response_mime_type": "text/plain", } model = genai.GenerativeModel( model_name="gemini-1.5-flash-8b-exp-0827", generation_config=generation_config, ) # AI Chatbot function def chat_with_ai(user_input): chat_session = model.start_chat( history=[ { "role": "user", "parts": [ prompt ], }, { "role": "model", "parts": [ "Sure, I can answer your question. \n", ], }, ] ) response = chat_session.send_message(user_input) return response.text # Gradio interface with gr.Blocks() as demo: available_weeks = get_available_weeks() # Tabs for Flashcards and Mock Test with gr.Tabs(): with gr.TabItem("Flashcards"): # Splash page to select the week with gr.Row(): week_file = gr.Dropdown(choices=available_weeks, label="Select CAM Week to Study") start_button = gr.Button("Start Studying") # Flashcard UI (hidden until week is selected) with gr.Column(visible=False) as flashcard_section: index = gr.State(0) question_output = gr.Textbox(label="Flashcard", interactive=False) answer_output = gr.Textbox(label="Answer", interactive=False) with gr.Row(): prev_btn = gr.Button("Previous") reveal_btn = gr.Button("Reveal Answer") next_btn = gr.Button("Next") with gr.Column(visible=True): chat_input = gr.Textbox(label="Ask a question to the A.I.") with gr.Row(): gr.Markdown(">Note: This A.I. has only been given the NBAA Management guide. Use the flashcards for specific week information.") chat_output = gr.Markdown(label="AI Response") chat_button = gr.Button("Ask AI") chat_button.click(chat_with_ai, inputs=[chat_input], outputs=[chat_output]) # Start button action to reveal the flashcard section start_button.click(lambda: gr.update(visible=True), inputs=[], outputs=flashcard_section) week_file.change(flashcard_ui, inputs=[week_file, index], outputs=[question_output, answer_output]) reveal_btn.click(reveal_answer, inputs=[week_file, index], outputs=answer_output) prev_btn.click(change_question, inputs=[week_file, index, gr.Number(-1, visible=False)], outputs=[index, question_output, answer_output]) next_btn.click(change_question, inputs=[week_file, index, gr.Number(1, visible=False)], outputs=[index, question_output, answer_output]) with gr.TabItem("Mock Test"): mock_index = gr.State(0) score = gr.State(0) incorrect_questions = gr.State([]) question_output = gr.Markdown(label="Question") with gr.Row(): answer_1 = gr.Button("Answer 1") answer_2 = gr.Button("Answer 2") with gr.Row(): answer_3 = gr.Button("Answer 3") answer_4 = gr.Button("Answer 4") result_output = gr.Markdown(visible=False) restart_button = gr.Button("Restart Test", visible=False) # Initialize the first question demo.load(update_question, inputs=[mock_index, score, incorrect_questions], outputs=[question_output, answer_1, answer_2, answer_3, answer_4]) # Handle answer selection for answer_btn in [answer_1, answer_2, answer_3, answer_4]: answer_btn.click( handle_answer, inputs=[answer_btn, mock_index, score, incorrect_questions], outputs=[question_output, restart_button, answer_1, answer_2, answer_3, answer_4, mock_index, score, incorrect_questions] ).then( update_question, inputs=[mock_index, score, incorrect_questions], outputs=[question_output, answer_1, answer_2, answer_3, answer_4] ) # Restart test button restart_button.click( restart_test, inputs=[], outputs=[mock_index, score, incorrect_questions, question_output, answer_1, answer_2, answer_3, answer_4, result_output, restart_button] ).then( update_question, inputs=[mock_index, score, incorrect_questions], outputs=[question_output, answer_1, answer_2, answer_3, answer_4] ) demo.launch()