File size: 24,831 Bytes
b0a11ad
 
 
 
 
7d60bc9
00899a8
7d60bc9
b0a11ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d858919
b0a11ad
d858919
b0a11ad
 
 
 
d858919
 
 
 
 
 
 
 
 
 
 
 
 
b0a11ad
 
746a5ef
b0a11ad
 
 
746a5ef
b0a11ad
 
 
d858919
b0a11ad
9a0181e
b0a11ad
 
 
 
9a0181e
b0a11ad
 
d858919
b0a11ad
9a0181e
b0a11ad
 
 
 
9a0181e
b0a11ad
 
d858919
f7e36d7
9a0181e
f7e36d7
 
 
 
 
 
 
 
9a0181e
f7e36d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e4c9cb
f7e36d7
9a0181e
f7e36d7
 
050a673
f7e36d7
 
e185b13
f7e36d7
e185b13
 
 
 
9a0181e
e185b13
f7e36d7
 
 
 
 
ca67d76
f7e36d7
 
 
e185b13
 
 
 
 
 
 
 
3e4c9cb
e185b13
 
050a673
e185b13
f7e36d7
d858919
f7e36d7
9a0181e
f7e36d7
 
 
 
 
 
9a0181e
f7e36d7
 
 
 
 
 
 
 
d858919
9a0181e
 
 
 
 
 
 
 
 
 
 
 
d858919
9a0181e
 
 
 
 
 
 
 
 
d858919
 
b5a5c0b
d858919
 
 
 
 
 
 
b5a5c0b
 
 
 
d858919
3e4c9cb
d858919
 
 
 
 
 
 
 
 
b0a11ad
 
 
c208b21
 
 
 
 
 
 
 
 
 
e0811c1
c208b21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e0811c1
 
c208b21
 
 
 
 
 
 
 
 
 
 
 
 
 
e0811c1
c208b21
 
 
 
 
 
e0811c1
 
c208b21
 
 
e0811c1
c208b21
d858919
 
 
 
 
 
 
 
 
3e4c9cb
 
 
 
c208b21
 
 
 
b0a11ad
 
c208b21
 
b0a11ad
 
 
9a0181e
 
 
 
 
 
 
 
b0a11ad
 
 
c208b21
b5a5c0b
050a673
b0a11ad
 
 
b5a5c0b
b0a11ad
 
 
 
b5a5c0b
b0a11ad
 
 
 
b5a5c0b
d858919
 
 
 
 
 
 
 
 
72d8d1e
b0a11ad
d858919
b0a11ad
d858919
b0a11ad
 
d858919
 
 
b5a5c0b
d858919
 
b0a11ad
 
 
c208b21
b5a5c0b
b0a11ad
 
 
 
b5a5c0b
b0a11ad
 
 
 
d858919
 
 
 
72d8d1e
b0a11ad
d858919
b0a11ad
d858919
b0a11ad
 
d858919
 
 
 
 
b0a11ad
 
 
c208b21
b5a5c0b
b0a11ad
 
 
 
d858919
 
 
 
72d8d1e
b0a11ad
d858919
b0a11ad
d858919
b0a11ad
 
d858919
 
 
 
 
f7e36d7
 
 
c208b21
f7e36d7
9a0181e
72d8d1e
f7e36d7
 
 
c208b21
f7e36d7
 
 
 
 
c208b21
b5a5c0b
f7e36d7
 
 
 
d858919
 
 
 
72d8d1e
050a673
d858919
3e4c9cb
d858919
3e4c9cb
f7e36d7
d858919
 
 
3e4c9cb
d858919
f7e36d7
 
 
c208b21
b5a5c0b
f7e36d7
 
 
 
d858919
 
 
 
72d8d1e
f7e36d7
d858919
f7e36d7
d858919
f7e36d7
 
d858919
 
 
 
 
9a0181e
c208b21
9a0181e
c208b21
b5a5c0b
9a0181e
 
 
 
b5a5c0b
9a0181e
 
 
 
d858919
 
 
 
72d8d1e
9a0181e
d858919
9a0181e
d858919
9a0181e
 
d858919
 
 
 
 
9a0181e
c208b21
9a0181e
c208b21
b5a5c0b
9a0181e
 
 
 
d858919
 
 
 
72d8d1e
9a0181e
d858919
9a0181e
d858919
9a0181e
 
d858919
 
 
 
 
 
b0a11ad
c208b21
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
import gradio as gr
import requests
import json
import os

# IMPORTANT: For deployment on Hugging Face Spaces,
# store your Google API Key as a Space Secret named 'GOOGLE_API_KEY'.
# Do NOT hardcode your API key directly in this file.
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY", "")

# Base function to call the Gemini API
def call_gemini_api(prompt):
    """
    Makes an API call to the Gemini 2.0 Flash model.
    """
    if not GOOGLE_API_KEY:
        raise ValueError("Google API Key is not configured. Please set it as a Space Secret or environment variable.")

    payload = {
        "contents": [
            {
                "role": "user",
                "parts": [{"text": prompt}]
            }
        ]
    }
    api_url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key={GOOGLE_API_KEY}"

    try:
        response = requests.post(
            api_url,
            headers={"Content-Type": "application/json"},
            data=json.dumps(payload)
        )
        response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)
        result = response.json()

        if result.get("candidates") and len(result["candidates"]) > 0 and \
           result["candidates"][0].get("content") and result["candidates"][0]["content"].get("parts") and \
           len(result["candidates"][0]["content"]["parts"]) > 0:
            return result["candidates"][0]["content"]["parts"][0]["text"]
        else:
            return "No content generated. The AI might not have understood the request or returned an empty response."

    except requests.exceptions.RequestException as e:
        return f"API request failed: {e}. Please check your internet connection or API key."
    except json.JSONDecodeError:
        return "Failed to parse API response. Invalid JSON received."
    except Exception as e:
        return f"An unexpected error occurred: {e}"


# --- Core Content Generation Functions ---

def generate_personalized_content(topic, content_type, difficulty, language, persona):
    """
    Generates personalized notes, quizzes, or explanations with specified difficulty, language, and persona.
    """
    if not topic.strip():
        return "Please enter a topic or question."

    persona_instruction = ""
    if persona == "Like a Professor":
        persona_instruction = "Adopt a formal, academic, and highly informative tone."
    elif persona == "Like a Storyteller":
        persona_instruction = "Explain it as if you are telling a captivating story, using engaging narrative."
    elif persona == "Like a Friend":
        persona_instruction = "Use a casual, friendly, and encouraging tone, simplifying complex ideas."
    elif persona == "Like a Scientist":
        persona_instruction = "Provide a precise, factual, and technical explanation, using scientific terminology where appropriate."
    elif persona == "Explain Like I'm 5":
        persona_instruction = "Explain it in extremely simple terms, as if to a 5-year-old, using basic vocabulary and analogies."

    prompt = f"As an expert educational assistant, {persona_instruction} generate {content_type} on the following topic: '{topic}' for a {difficulty} level learner. Provide the output in {language}."

    if content_type == 'notes':
        prompt += "\n\nProvide comprehensive, well-structured notes with key concepts, definitions, and examples. Use clear headings and bullet points. Format the output in Markdown for readability."
    elif content_type == 'quiz':
        prompt += "\n\nGenerate a short, challenging quiz (3-5 questions) with multiple-choice options and correct answers clearly marked. Include a mix of conceptual and application-based questions. Clearly label questions and answers (e.g., Q1:, A:, B:, C:, D:, Correct Answer:)."
    elif content_type == 'explanation':
        prompt += "\n\nProvide a detailed and easy-to-understand explanation, breaking down complex ideas into simpler terms. Use analogies if helpful. Format the output in Markdown for readability."
    
    return call_gemini_api(prompt)

def summarize_text_content(text_to_summarize, summary_length, language):
    """
    Summarizes provided text in a specified language.
    """
    if not text_to_summarize.strip():
        return "Please paste some text to summarize."

    prompt = f"Summarize the following text. Make the summary {summary_length} length. Focus on key points and main ideas. Provide the summary in {language}. Text:\n\n{text_to_summarize}"
    return call_gemini_api(prompt)

def generate_flashcards_content(flashcard_topic, language):
    """
    Generates flashcards (Q&A pairs) for a given topic in a specified language.
    """
    if not flashcard_topic.strip():
        return "Please enter a topic for flashcards."

    prompt = f"Generate 5-7 distinct question and answer flashcards for the topic: '{flashcard_topic}'. Format each flashcard as 'Q: [Question]\nA: [Answer]'. Use clear and concise language. Provide the flashcards in {language}."
    return call_gemini_api(prompt)

def ai_tutor_chat(message, history, language):
    """
    Handles conversational interaction for the AI Tutor in a specified language.
    """
    chat_history_gemini = []
    for human, ai in history:
        chat_history_gemini.append({"role": "user", "parts": [{"text": human}]})
        chat_history_gemini.append({"role": "model", "parts": [{"text": ai}]})
    
    chat_history_gemini.append({"role": "user", "parts": [{"text": message}]})

    system_instruction = f"You are a friendly and knowledgeable AI tutor. Your goal is to help users understand concepts, answer their questions, and guide them in their learning journey. Keep your responses concise and helpful. Respond in {language}."
    
    full_prompt_with_history = system_instruction + "\n\n"
    for entry in chat_history_gemini:
        if entry["role"] == "user":
            full_prompt_with_history += f"User: {entry['parts'][0]['text']}\n"
        elif entry["role"] == "model":
            full_prompt_with_history += f"Tutor: {entry['parts'][0]['text']}\n"
    
    full_prompt_with_history += f"User: {message}\nTutor:"

    try:
        response_text = call_gemini_api(full_prompt_with_history)
        return response_text
    except Exception as e:
        return f"Error in chat: {e}"


def generate_concept_map(topic, language):
    """
    Generates a concept map in Mermaid.js syntax for a given topic in a specified language.
    """
    if not topic.strip():
        return "Please enter a topic to generate a concept map."

    prompt = f"""Generate a concept map for the topic '{topic}' using Mermaid.js graph syntax.
    Focus on 5-10 key concepts and their direct relationships.
    Use `graph TD` for a top-down flow.
    Nodes should be defined as A[Concept Name] or B(Concept Name).
    Connections should be A --> B or A -- "Relationship" --> B.
    Ensure the output is ONLY the Mermaid.js code block, starting and ending with ```mermaid and ```.
    DO NOT include any introductory or concluding text outside the code block.
    Provide the concept names and relationships in {language}.

    Example format:
    ```mermaid
    graph TD
        A[Main Concept] --> B(Sub-concept 1)
        A --> C(Sub-concept 2)
        B --> D{{Detail 1}}
        C --> E[Detail 2]
    ```
    """
    
    try:
        raw_mermaid_code = call_gemini_api(prompt)
        if "```mermaid" not in raw_mermaid_code:
            rendered_output = f"```mermaid\n{raw_mermaid_code}\n```"
        else:
            rendered_output = raw_mermaid_code
            
        return rendered_output
    except Exception as e:
        error_msg = f"An error occurred during concept map generation: {e}"
        return error_msg


def generate_practice_problems(subject_topic, language):
    """
    Generates practice problems with solutions for a given subject/topic in a specified language.
    """
    if not subject_topic.strip():
        return "Please enter a subject or topic for practice problems."

    prompt = f"""Generate 3-5 practice problems for the subject/topic: '{subject_topic}'.
    For each problem, provide a clear problem statement and a step-by-step solution.
    Format clearly with headings for Problem and Solution. Use Markdown. Provide the problems and solutions in {language}.
    Example:
    ## Problem 1
    [Problem statement]
    ### Solution
    [Step-by-step solution]
    """
    return call_gemini_api(prompt)

def generate_essay_outline(topic, key_points, language):
    """
    Generates an essay/report outline for a given topic and optional key points.
    """
    if not topic.strip():
        return "Please enter a topic for the essay outline."

    prompt = f"Generate a detailed essay or report outline for the topic: '{topic}'. "
    if key_points.strip():
        prompt += f"Include the following key points: {key_points}. "
    prompt += f"Structure it with an Introduction, Body Paragraphs (with main ideas and supporting details), and Conclusion. Provide the outline in {language}. Use Markdown for formatting."
    return call_gemini_api(prompt)

def generate_vocabulary(topic_or_text, language):
    """
    Extracts key vocabulary from a topic or text and provides definitions.
    """
    if not topic_or_text.strip():
        return "Please enter a topic or paste text to extract vocabulary."

    prompt = f"Extract 5-10 key vocabulary terms from the following topic/text and provide a concise definition for each. Format as a list: '- Term: Definition'. Provide the terms and definitions in {language}. Topic/Text:\n\n{topic_or_text}"
    return call_gemini_api(prompt)

# --- Clear functions for each tab ---
def clear_personalized_content():
    return "", "notes", "Intermediate", "Default", "" # topic, content_type, difficulty, persona, output

def clear_summarizer():
    return "", "medium", "" # text_to_summarize, summary_length, output

def clear_flashcards():
    return "", "" # flashcard_topic, output

# AI Tutor Chat has its own clear button
# def clear_ai_tutor_chat():
#     return [] # history

def clear_concept_map():
    return "", "" # topic, rendered_output

def clear_practice_problems():
    return "", "" # subject_topic, output

def clear_essay_outline():
    return "", "", "" # topic, key_points, output

def clear_vocabulary():
    return "", "" # topic_or_text, output

# --- Gradio Interface Definition ---

# Custom CSS for a more attractive UI
custom_css = """
body {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    background: linear-gradient(135deg, #e0f2f7 0%, #c8e6c9 100%); /* Light, calming gradient */
}
h1 {
    color: #3f51b5 !important; /* Deeper indigo for main title */
    text-shadow: 1px 1px 2px rgba(0,0,0,0.1);
    font-size: 2.8rem !important; /* Slightly larger */
    margin-bottom: 10px; /* Reduced margin */
}
h3 { /* For tab headings */
    color: #4CAF50 !important; /* Green for section titles */
    font-size: 1.8rem !important;
    margin-bottom: 1.5rem;
    border-bottom: 2px solid #81C784; /* Subtle underline */
    padding-bottom: 0.5rem;
}
p {
    color: #555 !important;
    font-size: 1.1rem !important;
}
.gradio-container {
    border-radius: 15px !important;
    box-shadow: 0 10px 30px rgba(0,0,0,0.15) !important; /* Stronger shadow */
    overflow: hidden; /* Ensures rounded corners apply to inner content */
}
.gr-button {
    background-color: #4CAF50 !important; /* Green button */
    color: white !important;
    border: none !important;
    border-radius: 8px !important;
    padding: 12px 25px !important;
    font-size: 1.1rem !important;
    transition: all 0.3s ease !important;
    box-shadow: 0 4px 8px rgba(0, 150, 0, 0.2);
}
.gr-button:hover {
    background-color: #66BB6A !important; /* Lighter green on hover */
    transform: translateY(-2px); /* Subtle lift effect */
    box-shadow: 0 6px 12px rgba(0, 150, 0, 0.3);
}
.gr-textbox, .gr-dropdown, .gr-radio {
    border-radius: 8px !important;
    border: 1px solid #BDBDBD !important; /* Lighter border */
    box-shadow: inset 0 1px 3px rgba(0,0,0,0.05); /* Inner shadow for depth */
}
.gr-label {
    font-weight: bold !important;
    color: #424242 !important;
}
/* Style for the tabs */
.tabs {
    border-radius: 10px;
    background-color: #f5f5f5; /* Light background for tabs container */
    padding: 10px;
    box-shadow: inset 0 0 5px rgba(0,0,0,0.05);
}
.tab-nav button {
    border-radius: 8px 8px 0 0 !important;
    font-weight: 600 !important;
    color: #757575 !important;
    background-color: #e0e0e0 !important;
    transition: all 0.2s ease;
}
.tab-nav button.selected {
    background-color: #ffffff !important; /* White for selected tab */
    color: #4F46E5 !important; /* Primary color for selected tab text */
    border-bottom: 3px solid #4F46E5 !important; /* Underline for selected tab */
}
.gradio-container .prose { /* Target markdown output */
    line-height: 1.7;
    font-size: 1.05rem;
    color: #333;
}
.gradio-container .prose h2 {
    color: #3f51b5 !important;
    border-bottom: 1px dashed #9fa8da;
    padding-bottom: 5px;
    margin-top: 1.5em;
}
.gradio-container .prose h3 {
    color: #4CAF50 !important;
    margin-top: 1.2em;
}
/* Specific style for clear buttons */
.clear-button {
    background-color: #f44336 !important; /* Red for clear */
    box-shadow: 0 4px 8px rgba(244, 67, 54, 0.2);
}
.clear-button:hover {
    background-color: #ef5350 !important;
    box-shadow: 0 6px 12px rgba(244, 67, 54, 0.3);
}
/* Style for the main description below the title */
.gradio-container > div > p:nth-child(2) { /* Targeting the second <p> which is the description */
    margin-bottom: 2.5rem; /* More space below description */
}
"""


with gr.Blocks(theme=gr.themes.Monochrome(), css=custom_css) as demo:
    gr.Markdown(
        """
        <h1 style="text-align: center; color: #3f51b5; font-size: 2.8rem; font-weight: bold; text-shadow: 1px 1px 2px rgba(0,0,0,0.1);">EduGenius AI: Personalized Learning & Content Creator</h1>
        <p style="text-align: center; color: #555; font-size: 1.1rem;">Your intelligent companion for tailored study materials, interactive tutoring, and advanced learning aids.</p>
        """
    )

    # Define common language dropdown for multiple tabs
    language_dropdown = gr.Dropdown(
        ["English", "Urdu", "Spanish", "French", "German", "Chinese"],
        label="Select Output Language:",
        value="English",
        interactive=True
    )

    with gr.Tabs():
        # Tab 1: Personalized Content (Notes, Quiz, Explanation)
        with gr.TabItem("Personalized Content"):
            gr.Markdown("<h3>Generate Notes, Quizzes, or Explanations</h3>")
            topic_input_pc = gr.Textbox(
                label="Enter Topic or Question:", 
                placeholder="e.g., 'The principles of quantum mechanics'",
                lines=3
            )
            content_type_radio_pc = gr.Radio(
                ["notes", "quiz", "explanation"],
                label="Select Content Type:",
                value="notes"
            )
            difficulty_dropdown_pc = gr.Dropdown(
                ["Beginner", "Intermediate", "Advanced"],
                label="Select Difficulty Level (for Notes & Explanations):",
                value="Intermediate"
            )
            persona_dropdown_pc = gr.Dropdown(
                ["Default", "Like a Professor", "Like a Storyteller", "Like a Friend", "Like a Scientist", "Explain Like I'm 5"],
                label="Select Explanation Style (for Notes & Explanations):",
                value="Default"
            )
            
            with gr.Row():
                generate_button_pc = gr.Button("Generate Personalized Content", variant="primary")
                clear_button_pc = gr.Button("Clear All", variant="secondary", elem_classes="clear-button")
            
            personalized_output = gr.Markdown(value="", label="Generated Content:", show_copy_button=True)
            
            generate_button_pc.click(
                fn=generate_personalized_content,
                inputs=[topic_input_pc, content_type_radio_pc, difficulty_dropdown_pc, language_dropdown, persona_dropdown_pc],
                outputs=personalized_output
            )
            clear_button_pc.click(
                fn=clear_personalized_content,
                inputs=[],
                outputs=[topic_input_pc, content_type_radio_pc, difficulty_dropdown_pc, persona_dropdown_pc, personalized_output]
            )


        # Tab 2: Text Summarizer
        with gr.TabItem("Text Summarizer"):
            gr.Markdown("<h3>Summarize Any Text</h3>")
            text_to_summarize_input_ts = gr.Textbox(
                label="Paste Text to Summarize:",
                placeholder="Paste your article, document, or notes here...",
                lines=10
            )
            summary_length_radio_ts = gr.Radio(
                ["short", "medium", "long"],
                label="Summary Length:",
                value="medium"
            )
            with gr.Row():
                summarize_button_ts = gr.Button("Summarize Text", variant="primary")
                clear_button_ts = gr.Button("Clear All", variant="secondary", elem_classes="clear-button")
            
            summary_output = gr.Markdown(value="", label="Generated Summary:", show_copy_button=True)

            summarize_button_ts.click(
                fn=summarize_text_content,
                inputs=[text_to_summarize_input_ts, summary_length_radio_ts, language_dropdown],
                outputs=summary_output
            )
            clear_button_ts.click(
                fn=clear_summarizer,
                inputs=[],
                outputs=[text_to_summarize_input_ts, summary_length_radio_ts, summary_output]
            )

        # Tab 3: Flashcard Generator
        with gr.TabItem("Flashcard Generator"):
            gr.Markdown("<h3>Create Flashcards</h3>")
            flashcard_topic_input_fg = gr.Textbox(
                label="Enter Topic for Flashcards:",
                placeholder="e.g., 'Key figures of the Renaissance', 'Basic Algebra Formulas'",
                lines=3
            )
            with gr.Row():
                generate_flashcards_button_fg = gr.Button("Generate Flashcards", variant="primary")
                clear_button_fg = gr.Button("Clear All", variant="secondary", elem_classes="clear-button")
            
            flashcards_output = gr.Markdown(value="", label="Generated Flashcards:", show_copy_button=True)

            generate_flashcards_button_fg.click(
                fn=generate_flashcards_content,
                inputs=[flashcard_topic_input_fg, language_dropdown],
                outputs=flashcards_output
            )
            clear_button_fg.click(
                fn=clear_flashcards,
                inputs=[],
                outputs=[flashcard_topic_input_fg, flashcards_output]
            )
        
        # Tab 4: AI Tutor Chatbot
        with gr.TabItem("AI Tutor Chat"):
            gr.Markdown("<h3>Chat with Your AI Tutor</h3>")
            gr.ChatInterface(
                fn=lambda message, history: ai_tutor_chat(message, history, language_dropdown.value),
                chatbot=gr.Chatbot(height=400, show_copy_button=True),
                textbox=gr.Textbox(placeholder="Ask me anything about your studies!", container=False, scale=7),
                title="Your Personal AI Tutor",
                description="Engage in a conversational learning experience.",
                theme="soft", # ChatInterface has its own theme parameter
                examples=["Explain Newton's Laws.", "What is photosynthesis?", "Help me understand recursion in programming."]
            )

        # Tab 5: Concept Map Generator
        with gr.TabItem("Concept Map Generator"):
            gr.Markdown("<h3>Visualize Concepts with a Mind Map</h3>")
            concept_map_topic_input_cm = gr.Textbox(
                label="Enter Topic for Concept Map:",
                placeholder="e.g., 'Machine Learning Algorithms', 'Human Circulatory System'",
                lines=3
            )
            with gr.Row():
                generate_concept_map_button_cm = gr.Button("Generate Concept Map", variant="primary")
                clear_button_cm = gr.Button("Clear All", variant="secondary", elem_classes="clear-button")
            
            concept_map_rendered_output = gr.Markdown(value="", label="Rendered Concept Map:", show_copy_button=True)
            
            generate_concept_map_button_cm.click(
                fn=lambda topic: generate_concept_map(topic, language_dropdown.value),
                inputs=[concept_map_topic_input_cm],
                outputs=concept_map_rendered_output
            )
            clear_button_cm.click(
                fn=clear_concept_map,
                inputs=[],
                outputs=[concept_map_topic_input_cm, concept_map_rendered_output]
            )

        # Tab 6: Practice Problem Generator
        with gr.TabItem("Practice Problems"):
            gr.Markdown("<h3>Generate Practice Problems with Solutions</h3>")
            problem_subject_input_pp = gr.Textbox(
                label="Enter Subject/Topic for Problems:",
                placeholder="e.g., 'Algebra Equations', 'Physics Kinematics', 'Python List Comprehensions'",
                lines=3
            )
            with gr.Row():
                generate_problems_button_pp = gr.Button("Generate Problems", variant="primary")
                clear_button_pp = gr.Button("Clear All", variant="secondary", elem_classes="clear-button")
            
            problems_output = gr.Markdown(value="", label="Generated Problems & Solutions:", show_copy_button=True)

            generate_problems_button_pp.click(
                fn=generate_practice_problems,
                inputs=[problem_subject_input_pp, language_dropdown],
                outputs=problems_output
            )
            clear_button_pp.click(
                fn=clear_practice_problems,
                inputs=[],
                outputs=[problem_subject_input_pp, problems_output]
            )
        
        # Tab 7: Essay/Report Outline Generator
        with gr.TabItem("Essay Outline Generator"):
            gr.Markdown("<h3>Create Structured Essay/Report Outlines</h3>")
            essay_topic_input_eo = gr.Textbox(
                label="Enter Essay Topic:",
                placeholder="e.g., 'The Impact of AI on Education'",
                lines=3
            )
            essay_key_points_input_eo = gr.Textbox(
                label="Optional: Enter Key Points (comma-separated):",
                placeholder="e.g., 'personalization, efficiency, challenges, future'",
                lines=2
            )
            with gr.Row():
                generate_outline_button_eo = gr.Button("Generate Outline", variant="primary")
                clear_button_eo = gr.Button("Clear All", variant="secondary", elem_classes="clear-button")
            
            outline_output = gr.Markdown(value="", label="Generated Essay Outline:", show_copy_button=True)

            generate_outline_button_eo.click(
                fn=generate_essay_outline,
                inputs=[essay_topic_input_eo, essay_key_points_input_eo, language_dropdown],
                outputs=outline_output
            )
            clear_button_eo.click(
                fn=clear_essay_outline,
                inputs=[],
                outputs=[essay_topic_input_eo, essay_key_points_input_eo, outline_output]
            )

        # Tab 8: Vocabulary Builder
        with gr.TabItem("Vocabulary Builder"):
            gr.Markdown("<h3>Extract & Define Key Vocabulary</h3>")
            vocab_topic_or_text_input_vb = gr.Textbox(
                label="Enter Topic or Paste Text:",
                placeholder="e.g., 'Genetics' or paste a paragraph about it...",
                lines=5
            )
            with gr.Row():
                generate_vocab_button_vb = gr.Button("Generate Vocabulary", variant="primary")
                clear_button_vb = gr.Button("Clear All", variant="secondary", elem_classes="clear-button")
            
            vocab_output = gr.Markdown(value="", label="Generated Vocabulary & Definitions:", show_copy_button=True)

            generate_vocab_button_vb.click(
                fn=generate_vocabulary,
                inputs=[vocab_topic_or_text_input_vb, language_dropdown],
                outputs=vocab_output
            )
            clear_button_vb.click(
                fn=clear_vocabulary,
                inputs=[],
                outputs=[vocab_topic_or_text_input_vb, vocab_output]
            )

# Launch the Gradio application
demo.launch()