Spaces:
Sleeping

File size: 13,535 Bytes
44916f9
0bb9672
44916f9
fe511a4
44916f9
 
 
 
ddbf640
8f0dfd3
44916f9
 
 
 
 
f084f6f
44916f9
 
 
 
 
 
 
 
 
 
 
f084f6f
44916f9
 
 
 
 
 
 
 
 
 
 
f084f6f
 
 
 
44916f9
 
f084f6f
44916f9
 
 
 
 
 
ee5dfa2
44916f9
 
f084f6f
 
44916f9
b14abcf
44916f9
 
 
 
0bb9672
f084f6f
44916f9
 
 
 
 
 
 
 
 
f084f6f
44916f9
 
 
f084f6f
 
44916f9
 
 
 
 
 
f084f6f
44916f9
 
f084f6f
44916f9
 
 
 
f084f6f
 
44916f9
 
 
f084f6f
44916f9
f084f6f
 
 
44916f9
f084f6f
44916f9
f686429
f084f6f
 
 
 
 
ea60211
 
 
f084f6f
 
 
 
55f19cf
 
f084f6f
 
 
c96d67b
f084f6f
 
 
 
 
c96d67b
f084f6f
f686429
f084f6f
f822456
f084f6f
61829f5
f084f6f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44916f9
 
f084f6f
44916f9
f084f6f
44916f9
f084f6f
98fb148
f084f6f
44916f9
 
 
 
9edd93a
80031df
f084f6f
 
f822456
f084f6f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f822456
f084f6f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f822456
f084f6f
 
 
 
 
f822456
f084f6f
 
 
 
f822456
f084f6f
f822456
0a2dfeb
 
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
import os
import json
import uuid
import time
from datetime import datetime
import requests
import tempfile

import gradio as gr
from huggingface_hub import HfApi, hf_hub_download

# ---------- CONFIG ----------
HF_WRITE_TOKEN = os.environ.get("HF_WRITE_TOKEN")  # write token for dataset commits
REPO_ID = "abhidgp1978/TeachMate_AI"               # dataset repo to store homework.jsonl
REPO_TYPE = "dataset"
FILE_NAME = "homework.jsonl"

GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
MODEL = "llama3-8b-8192"
INFERENCE_URL = "https://api.groq.com/openai/v1/chat/completions"
# ----------------------------

assert HF_WRITE_TOKEN is not None, "Set HF_WRITE_TOKEN env var in Space settings."
assert GROQ_API_KEY is not None, "Set GROQ_API_KEY env var in Space settings."

api = HfApi()

def call_groq_api(prompt, temperature=0.7, max_tokens=256):
    payload = {
        "model": MODEL,
        "messages": [{"role": "user", "content": prompt}],
        "temperature": temperature,
        "max_tokens": max_tokens,
        "stop": None,
    }
    headers = {
        "Authorization": f"Bearer {GROQ_API_KEY}",
        "Content-Type": "application/json",
    }
    resp = requests.post(INFERENCE_URL, headers=headers, json=payload, timeout=60)
    resp.raise_for_status()
    data = resp.json()
    return data["choices"][0]["message"]["content"]

# Dataset helpers
def read_remote_homework():
    try:
        local_path = hf_hub_download(repo_id=REPO_ID, filename=FILE_NAME, repo_type=REPO_TYPE, token=HF_WRITE_TOKEN)
        with open(local_path, "r", encoding="utf-8") as f:
            lines = f.read().splitlines()
        records = [json.loads(line) for line in lines if line.strip()]
        return records
    except Exception:
        return []

def append_and_push_record(record: dict):
    existing = read_remote_homework()
    existing.append(record)

    with tempfile.NamedTemporaryFile(mode="w+", delete=False, encoding="utf-8", suffix=".jsonl") as tmpf:
        for rec in existing:
            tmpf.write(json.dumps(rec, ensure_ascii=False) + "\n")
        tmp_path = tmpf.name

    commit_message = f"Add homework record {record.get('id')} by {record.get('teacher_email', 'unknown')}"
    try:
        api.upload_file(
            path_or_fileobj=tmp_path,
            path_in_repo=FILE_NAME,
            repo_id=REPO_ID,
            repo_type=REPO_TYPE,
            token=HF_WRITE_TOKEN,
            commit_message=commit_message,
        )
        return True, "Question is saved."
    except Exception as e:
        return False, f"Failed to push to dataset repo: {e}"

# Teacher helpers
def generate_prompt(subject, brief, num_questions=5, complexity="Medium"):
    return (
        f"You are an experienced K-12 teacher. Create {num_questions} diverse homework questions "
        f"for a {subject} class based on the brief below, with {complexity} complexity. Include a short instruction line at the top. "
        f"Mix question types (short answer, problem solving, multiple choice). "
        f"Be concise and teacher-friendly.\n\n"
        f"Brief: {brief}\n\n"
        f"Output format:\n1) Question text\n2) Question text\n..."
    )

def generate_homework(subject, brief, num_questions=5, complexity="Medium"):
    prompt = generate_prompt(subject, brief, num_questions, complexity)
    generated = call_groq_api(prompt, temperature=0.7, max_tokens=350)
    return generated.strip()

# Student helpers
def parse_questions(text):
    lines = text.strip().splitlines()
    questions = []
    for line in lines:
        if line.strip() == "":
            continue
        # Matches "1)" or "10)" etc
        if line[0].isdigit() and ")" in line:
            parts = line.split(")", 1)
            if len(parts) > 1:
                questions.append(parts[1].strip())
    return questions

def filter_homework_names(subject, grade):
    records = read_remote_homework()
    # Filter by subject and grade
    filtered = [r for r in records if r.get("subject") == subject and r.get("grade") == grade]
    # Return list of homework_name strings (including duplicates)
    names = [r.get("homework_name", "Unnamed Homework") for r in filtered]
    return names

def get_homework_by_name(subject, grade, homework_name):
    records = read_remote_homework()
    # Return list of all records matching the subject, grade, and homework_name (duplicates allowed)
    matches = [r for r in records if r.get("subject") == subject and r.get("grade") == grade and r.get("homework_name") == homework_name]
    return matches

def generate_hint_for_roughwork(text):
    prompt = f"You are a helpful tutor. Give hints or suggestions based on the following student input:\n\n{text}"
    return call_groq_api(prompt, temperature=0.7, max_tokens=120)

def analyze_answers(questions, answers, time_taken_seconds):
    score = sum(1 for a in answers if a.strip())
    needs_attention = score < (len(questions) * 0.6)
    result = f"Score: {score}/{len(questions)}."
    return result, needs_attention

# UI Setup
with gr.Blocks() as demo:
    gr.Markdown("# TeachMate AI")

    student_results = []

    with gr.Tabs():
        # Teacher tab
        with gr.TabItem("Teacher"):
            with gr.Row():
                with gr.Column(scale=1):
                    name_in = gr.Textbox(label="Teacher Name")
                    email_in = gr.Textbox(label="Teacher Email")
                    subject_in = gr.Dropdown(label="Subject", choices=["Mathematics","Science","English","History","Geography","Other"], value="Mathematics")
                    grade_in = gr.Dropdown(label="Grade", choices=[f"Grade {i}" for i in range(1,13)], value="Grade 5")
                    homework_name_in = gr.Textbox(label="Homework Name (e.g., Homework 1)")
                    complexity_in = gr.Dropdown(label="Complexity", choices=["Easy", "Medium", "Hard"], value="Medium")
                    brief_in = gr.Textbox(label="Homework Brief (describe topic & grade)", lines=4)
                    gen_btn = gr.Button("Generate Homework", variant="primary")

                with gr.Column(scale=1):
                    generated_out = gr.Textbox(label="Generated / Editable Questions", lines=20, interactive=True)
                    save_btn = gr.Button("Save to Dataset", variant="secondary")
                    status = gr.Textbox(label="Status / Logs", interactive=False)
                    results_out = gr.Textbox(label="Student Results & Attention Warnings", lines=10, interactive=False)

            def on_generate(name, email, subject, grade, hw_name, complexity, brief):
                if not brief.strip():
                    return "Please enter a brief"
                return generate_homework(subject, brief, num_questions=5, complexity=complexity)

            def on_save(name, email, subject, grade, hw_name, complexity, brief, questions):
                if not hw_name.strip():
                    return "Please enter a homework name"
                rec = {
                    "id": str(uuid.uuid4()),
                    "teacher_name": name,
                    "teacher_email": email,
                    "subject": subject,
                    "grade": grade,
                    "homework_name": hw_name,
                    "complexity": complexity,
                    "brief": brief,
                    "final_questions": questions,
                    "created_at": datetime.now().isoformat(),
                }
                success, msg = append_and_push_record(rec)
                return msg

            def update_teacher_results():
                if not student_results:
                    return "No student submissions yet."
                lines = []
                for r in student_results:
                    line = (f"Student: {r['student_name']} | Grade: {r['student_grade']} | "
                            f"Score: {r['score']}/{r['total_questions']} | "
                            f"Attention: {'YES' if r['needs_attention'] else 'NO'}")
                    lines.append(line)
                return "\n".join(lines)

            gen_btn.click(on_generate, inputs=[name_in, email_in, subject_in, grade_in, homework_name_in, complexity_in, brief_in], outputs=generated_out)
            save_btn.click(on_save, inputs=[name_in, email_in, subject_in, grade_in, homework_name_in, complexity_in, brief_in, generated_out], outputs=status)

        # Student tab
        with gr.TabItem("Student"):
            with gr.Row():
                with gr.Column(scale=1):
                    student_name = gr.Textbox(label="Student Name")
                    student_grade = gr.Dropdown(label="Grade", choices=[f"Grade {i}" for i in range(1,13)], value="Grade 5")
                    student_email = gr.Textbox(label="Student Email")
                    student_subject = gr.Dropdown(label="Subject", choices=["Mathematics","Science","English","History","Geography","Other"], value="Mathematics")

                    homework_name_dd = gr.Dropdown(label="Select Homework", choices=[], value=None, interactive=True)

                with gr.Column(scale=1):
                    questions_box = gr.Textbox(label="Questions", lines=15, interactive=False)
                    answers_box = gr.Textbox(label="Your Answers (one per line)", lines=15, interactive=True)
                    submit_btn = gr.Button("Submit Answers")
                    result_out = gr.Textbox(label="Result", lines=4, interactive=False)

            current_questions = gr.State([])
            start_time = gr.State(None)

            def load_homework_names(subject, grade):
                names = filter_homework_names(subject, grade)
                if not names:
                    # FIX: Return a single gr.update object to update the choices, interactive, and value properties.
                    # This ensures the choices list is correctly updated before a value is selected.
                    return gr.update(choices=[], interactive=False, value=None), "", [], None

                default_name = names[0]
                matches = get_homework_by_name(subject, grade, default_name)
                questions_text = ""
                questions = []
                if matches:
                    questions_text = "\n\n".join(m.get("final_questions", "") for m in matches)
                    questions = parse_questions(questions_text)
                start = time.time()
                
                # FIX: Return a single gr.update object to update the choices, interactive, and value properties.
                return gr.update(choices=names, interactive=True, value=default_name), questions_text, questions, start

            def load_questions_by_name(hw_name, subject, grade):
                if hw_name is None:
                    # FIX: Return a consistent set of outputs for the outputs list.
                    return "", [], None
                
                matches = get_homework_by_name(subject, grade, hw_name)
                if not matches:
                    return "", [], None
                questions_text = "\n\n".join(m.get("final_questions", "") for m in matches)
                questions = parse_questions(questions_text)
                start = time.time()
                return questions_text, questions, start

            def submit_answers(questions, answers, start, student_name_val, student_grade_val):
                if start is None:
                    start = time.time()
                time_taken = time.time() - start
                ans_list = answers.splitlines()
                res, needs_attention = analyze_answers(questions, ans_list, time_taken)
                student_results.append({
                    "student_name": student_name_val,
                    "student_grade": student_grade_val,
                    "score": sum(1 for a in ans_list if a.strip()),
                    "total_questions": len(questions),
                    "needs_attention": needs_attention
                })
                return res

            # FIX: Corrected the outputs list to match the return values of load_homework_names.
            # The second `questions_box` was removed as it was likely a duplicate.
            student_subject.change(load_homework_names, inputs=[student_subject, student_grade], outputs=[homework_name_dd, questions_box, current_questions, start_time])
            student_grade.change(load_homework_names, inputs=[student_subject, student_grade], outputs=[homework_name_dd, questions_box, current_questions, start_time])
            
            homework_name_dd.change(load_questions_by_name, inputs=[homework_name_dd, student_subject, student_grade], outputs=[questions_box, current_questions, start_time])
            
            submit_btn.click(submit_answers, inputs=[current_questions, answers_box, start_time, student_name, student_grade], outputs=result_out)

        # Rough Work tab
        with gr.TabItem("Rough Work"):
            rough_input = gr.Textbox(label="Enter your questions or doubts here", lines=10, interactive=True)
            get_hint_btn = gr.Button("Get Hint")
            hint_output = gr.Textbox(label="AI-generated Hint", lines=5, interactive=False)

            def generate_hint(text):
                if not text.strip():
                    return "Please enter some text for hints."
                return generate_hint_for_roughwork(text)

            get_hint_btn.click(generate_hint, inputs=rough_input, outputs=hint_output)

if __name__ == "__main__":
    demo.launch()