Spaces:
Sleeping
Sleeping
Download app.py from abhidgp1978/TeachMate_AI: direct link, hf CLI and curl.
- Browser
- Download file 13.5 kB
-
https://huggingface.co/spaces/abhidgp1978/TeachMate_AI/resolve/main/app.py
- Command line
-
hf download hf://spaces/abhidgp1978/TeachMate_AI/app.py
-
curl -L -o app.py https://huggingface.co/spaces/abhidgp1978/TeachMate_AI/resolve/main/app.py
13.5 kB
| 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() | |