File size: 6,569 Bytes
f29a992
 
 
1449f93
f29a992
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd71f5d
f29a992
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd71f5d
 
f29a992
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120595f
 
 
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
import os
from groq import Groq
client = Groq(api_key=os.environ.get("GROQ_API_KEY"))



SYSTEM_PROMPTS = {
 
    "πŸ“– Explain": """
You are a friendly, patient study tutor. Your job is to explain any topic
clearly to a student who is hearing it for the first time.
 
Rules:
- Use simple everyday language. Avoid jargon unless you define it immediately.
- Break the explanation into short paragraphs.
- Use a real-world analogy to make the concept concrete.
- End with one "Key takeaway" sentence in bold.
- Keep the total response under 300 words.
""",
 
    "πŸ§ͺ Quiz Me": """
You are a quiz master helping a student test their understanding.
 
When given a topic, generate exactly 5 multiple-choice questions. Format:
 
Q1. [Question]
A) ...  B) ...  C) ...  D) ...
βœ… Answer: [Letter] β€” [Brief explanation]
 
Rules:
- Questions should cover different aspects of the topic.
- Only one option should be clearly correct.
- The explanation after the answer must be one sentence.
- Do not repeat options across questions.
""",
 
    "πŸ“ Summarise": """
You are an expert note-taker. Summarise the given topic or text for a student
who needs to revise quickly.
 
Format your summary as:
β€’ 3–5 bullet points covering the main ideas
β€’ One "Remember this" box at the end (a single memorable fact or formula)
 
Rules:
- Every bullet must be one concise sentence.
- Use student-friendly language.
- Do not add padding or filler phrases like "In conclusion...".
""",
 
    "πŸ—‚οΈ Flashcards": """
You are a flashcard generator. Given a topic, produce 6 study flashcards.
 
Format each card as:
FRONT: [Term or concept]
BACK: [Clear, concise definition or explanation β€” max 2 sentences]
 
Rules:
- Cover a variety of sub-topics within the given subject.
- Keep BACK answers short enough to memorise in one reading.
- Number each card (Card 1, Card 2, …).
""",
 
    "πŸ” Ask a Doubt": """
You are a helpful teaching assistant. Answer the student's specific question
directly and accurately.
 
Rules:
- Answer only what is asked. Do not pad with unrelated information.
- If the question has a common misconception, address it briefly.
- Use examples or analogies if they make the answer clearer.
- Keep the response under 200 words.
""",
}

def study_assistant(topic: str, mode: str) -> str:
    """
    Sends a prompt to Groq and returns the response text.
 
    Args:
        topic: The student's question or topic to study.
        mode:  One of the keys in SYSTEM_PROMPTS (matches the dropdown).
 
    Returns:
        The model's response as a plain string.
    """
    if not topic.strip():
        return "⚠️ Please enter a topic or question first."
 
    system_instruction = SYSTEM_PROMPTS.get(mode, SYSTEM_PROMPTS["πŸ“– Explain"])
 
    try:
        response = client.chat.completions.create(
            model="llama-3.1-8b-instant",   # Fast, free-tier Groq model
            messages=[
                {"role": "system", "content": system_instruction},
                {"role": "user",   "content": topic},
            ],
            temperature=0.7,    # Balanced creativity
            max_tokens=1024,    # Enough for flashcards / quiz output
        )
        return response.choices[0].message.content
 
    except Exception as error:
        return f"❌ API error: {error}\n\nCheck that your GROQ_API_KEY secret is set correctly."

import gradio as gr
 
with gr.Blocks(title="πŸ“š Personalized Study Assistant") as demo:
 
    # ── Header ────────────────────────────────────────────────
    gr.Markdown("""
    # πŸ“š Personalized Study Assistant
    *Powered by Groq (LLaMA 3.1) β€’ Built for ADYPU LLM Practicals*
 
    Choose a study mode, enter your topic or question, and hit **Generate**.
    """)
 
    # ── Controls ──────────────────────────────────────────────
    with gr.Row():
        mode_selector = gr.Dropdown(
            choices=list(SYSTEM_PROMPTS.keys()),
            value="πŸ“– Explain",
            label="Study Mode",
            info="Pick how you want to interact with the material.",
        )
 
    topic_input = gr.Textbox(
        label="Your topic or question",
        placeholder="e.g.  Newton's laws of motion  |  What is photosynthesis?  |  Explain recursion",
        lines=2,
    )
 
    generate_btn = gr.Button("⚑ Generate", variant="primary")
 
    # ── Output ────────────────────────────────────────────────
    output_box = gr.Textbox(
    label="Study Assistant Response",
    lines=18,
    )
 
    # ── Mode description cards ────────────────────────────────
    with gr.Accordion("ℹ️ What does each mode do?", open=False):
        gr.Markdown("""
        | Mode | What it does |
        |------|-------------|
        | πŸ“– Explain | Breaks down any topic using simple language + a real-world analogy |
        | πŸ§ͺ Quiz Me | Generates 5 multiple-choice questions with answers & explanations |
        | πŸ“ Summarise | Bullet-point revision notes + a key fact to remember |
        | πŸ—‚οΈ Flashcards | 6 FRONT/BACK flashcards ready to memorise |
        | πŸ” Ask a Doubt | Direct answer to your specific question |
        """)
 
    # ── Example buttons ───────────────────────────────────────
    gr.Examples(
        examples=[
            ["Photosynthesis", "πŸ“– Explain"],
            ["Newton's Laws of Motion", "πŸ§ͺ Quiz Me"],
            ["The Water Cycle", "πŸ“ Summarise"],
            ["Machine Learning", "πŸ—‚οΈ Flashcards"],
            ["What is the difference between RAM and ROM?", "πŸ” Ask a Doubt"],
        ],
        inputs=[topic_input, mode_selector],
        label="Try an example",
    )
 
    # ── Wire up the button ────────────────────────────────────
    generate_btn.click(
        fn=study_assistant,
        inputs=[topic_input, mode_selector],
        outputs=output_box,
    )
 
    # Also trigger on Enter key in the text box
    topic_input.submit(
        fn=study_assistant,
        inputs=[topic_input, mode_selector],
        outputs=output_box,
    )

demo.launch(server_name="0.0.0.0", server_port=7860)