File size: 9,256 Bytes
d5977e3
 
 
1da0920
d8ca418
d5977e3
36ab372
 
 
 
 
d5977e3
36ab372
d5977e3
36ab372
d5977e3
 
 
36ab372
d5977e3
d8ca418
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1da0920
 
 
 
 
 
 
 
200f09a
1da0920
 
 
 
 
 
 
 
 
 
 
 
 
6582ca7
1da0920
8267305
c0746ee
1da0920
d8ca418
 
6582ca7
 
6cba9e7
8267305
 
6582ca7
 
200f09a
6582ca7
 
 
 
 
 
 
 
 
 
 
c0746ee
8267305
650e31e
c0746ee
650e31e
6582ca7
9679e18
 
6582ca7
c0746ee
9679e18
6582ca7
9679e18
f7fc3c9
1e63407
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5977e3
 
36ab372
 
1da0920
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e63407
 
 
 
 
 
 
3446f0f
1da0920
 
 
 
 
 
 
 
 
 
6582ca7
 
1da0920
513dc9e
 
 
 
 
 
6582ca7
1da0920
 
 
 
6582ca7
 
1da0920
513dc9e
 
 
6582ca7
 
8267305
 
6582ca7
8267305
513dc9e
6582ca7
1da0920
650e31e
 
 
6582ca7
650e31e
 
6582ca7
650e31e
 
8267305
d8ca418
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
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()