Download app.py from dgith/mwlm: direct link, hf CLI and curl.
- Browser
- Download file 12.7 kB
-
https://huggingface.co/spaces/dgith/mwlm/resolve/main/app.py
- Command line
-
hf download hf://spaces/dgith/mwlm/app.py
-
curl -L -o app.py https://huggingface.co/spaces/dgith/mwlm/resolve/main/app.py
12.7 kB
| import gradio as gr | |
| import torch | |
| from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline | |
| import random | |
| import os | |
| # Comprehensive CBC Curriculum Data | |
| CBC_CURRICULUM = { | |
| "grade1": { | |
| "Mathematics": [ | |
| "Numbers: Counting, reading and writing numbers 1-100", | |
| "Addition and subtraction of whole numbers up to 20", | |
| "Measurement: Length, mass, capacity", | |
| "Geometry: 2D shapes recognition" | |
| ], | |
| "English": [ | |
| "Phonics: Letter recognition and sounds", | |
| "Reading: Simple sentences and stories", | |
| "Writing: Letter formation and simple words", | |
| "Speaking: Oral communication skills" | |
| ], | |
| "Kiswahili": [ | |
| "Herufi na sauti", | |
| "Kusoma kwa sauti", | |
| "Kuandika herufi na maneno rahisi", | |
| "Nomino na vitendo" | |
| ] | |
| }, | |
| "grade2": { | |
| "Mathematics": [ | |
| "Numbers: Counting up to 500", | |
| "Addition and subtraction up to 100", | |
| "Fractions: Halves and quarters", | |
| "Time: Reading clocks" | |
| ], | |
| "English": [ | |
| "Grammar: Nouns and verbs", | |
| "Reading: Short stories and poems", | |
| "Writing: Simple sentences", | |
| "Vocabulary: Word families" | |
| ], | |
| "Kiswahili": [ | |
| "Nomino na vitendo", | |
| "Kusoma hadithi fupi", | |
| "Kuandika aya na sentensi" | |
| ] | |
| }, | |
| "grade3": { | |
| "Mathematics": [ | |
| "Numbers: Counting up to 1000", | |
| "Multiplication and division up to 100", | |
| "Fractions: Comparing and ordering", | |
| "Geometry: 3D shapes" | |
| ], | |
| "English": [ | |
| "Grammar: Parts of speech", | |
| "Reading: Comprehension skills", | |
| "Writing: Paragraphs", | |
| "Vocabulary: Synonyms and antonyms" | |
| ], | |
| "Kiswahili": [ | |
| "Nomino, vitendo na cviambishi", | |
| "Kusoma kwa kina", | |
| "Kuandika insha" | |
| ] | |
| } | |
| } | |
| # Detailed topic explanations for better questioning | |
| TOPIC_EXPLANATIONS = { | |
| "Nomino na vitendo": { | |
| "description": "Nomino ni majina ya vitu, wanyama, watu au mahali. Vitendo ni maneno yanayoonesha tendo kama 'kula', 'soma', 'cheza'", | |
| "examples": ["Mtu", "mji", "gari", "soma", "cheza", "kula"], | |
| "grade1": "Jifunze kutambua nomino rahisi kama 'mji', 'mtu', 'gari' na vitendo kama 'soma', 'cheza'", | |
| "grade2": "Tambua nomino za watu, vitu, wanyama na vitendo katika sentensi", | |
| "grade3": "Tumia nomino na vitendo kujenga sentensi zenye maana" | |
| }, | |
| "Numbers: Counting, reading and writing numbers 1-100": { | |
| "description": "Kujifunza kuhesabu, kusoma na kuandika nambari kutoka 1 hadi 100", | |
| "examples": ["moja", "kumi", "ishirini", "hamsini", "mia moja"], | |
| "grade1": "Hesabu kutoka 1 hadi 100 na uandike kwa tarakimu", | |
| "grade2": "Soma na andika nambari hadi 500", | |
| "grade3": "Linganisha na panga nambari hadi 1000" | |
| } | |
| } | |
| class CBCLearningAssistant: | |
| def __init__(self): | |
| self.model = None | |
| self.tokenizer = None | |
| self.pipeline = None | |
| self.load_model() | |
| def load_model(self): | |
| """Load a lightweight model suitable for HF Spaces""" | |
| try: | |
| # Use a smaller, more efficient model | |
| from transformers import pipeline | |
| self.pipeline = pipeline( | |
| "text-generation", | |
| model="google/gemma-2b-it", | |
| torch_dtype=torch.bfloat16, | |
| device_map="auto", | |
| max_new_tokens=100 | |
| ) | |
| print("Model loaded successfully!") | |
| except Exception as e: | |
| print(f"Error loading model: {e}") | |
| self.pipeline = None | |
| def get_topic_info(self, topic, grade): | |
| """Get detailed information about a topic""" | |
| for topic_key, info in TOPIC_EXPLANATIONS.items(): | |
| if topic_key in topic: | |
| return info | |
| return None | |
| def generate_contextual_prompt(self, user_input, grade, subject, topic): | |
| """Generate a contextual prompt for the model""" | |
| topic_info = self.get_topic_info(topic, grade) | |
| if topic_info: | |
| description = topic_info.get("description", "") | |
| grade_level_desc = topic_info.get(f"grade{grade}", "") | |
| examples = ", ".join(topic_info.get("examples", [])[:3]) | |
| else: | |
| description = f"Learning about {topic} in {subject}" | |
| grade_level_desc = f"Grade {grade} level content" | |
| examples = "common examples" | |
| prompt = f"""You are a Socratic learning assistant for Kenya's CBC curriculum. | |
| Student age: {int(grade) + 5} years old | |
| Subject: {subject} | |
| Topic: {topic} | |
| Description: {description} | |
| Grade level focus: {grade_level_desc} | |
| Student says: "{user_input}" | |
| Respond with ONE thoughtful question that guides their thinking. | |
| DO NOT give direct answers. | |
| Ask open-ended questions that encourage exploration. | |
| Examples of what to ask: | |
| - "What do you notice about {examples}?" | |
| - "Can you think of something similar in your daily life?" | |
| - "How would you explain this to a friend?" | |
| Question:""" | |
| return prompt | |
| def generate_socratic_response(self, user_input, grade, subject, topic): | |
| """Generate a proper Socratic response using the model""" | |
| if self.pipeline is None: | |
| # Fallback to rule-based generation | |
| return self.generate_rule_based_response(user_input, grade, subject, topic) | |
| try: | |
| prompt = self.generate_contextual_prompt(user_input, grade, subject, topic) | |
| # Generate response | |
| response = self.pipeline( | |
| prompt, | |
| max_new_tokens=80, | |
| temperature=0.7, | |
| do_sample=True, | |
| pad_token_id=128001 # Gemma pad token | |
| ) | |
| generated_text = response[0]['generated_text'] | |
| # Extract just the question part | |
| if "Question:" in generated_text: | |
| question = generated_text.split("Question:")[-1].strip() | |
| else: | |
| question = generated_text.strip() | |
| return question if question else "What makes you curious about this topic?" | |
| except Exception as e: | |
| print(f"Error in model generation: {e}") | |
| return self.generate_rule_based_response(user_input, grade, subject, topic) | |
| def generate_rule_based_response(self, user_input, grade, subject, topic): | |
| """Rule-based Socratic questioning when model fails""" | |
| # Get topic info | |
| topic_info = self.get_topic_info(topic, grade) | |
| if topic == "Nomino na vitendo": | |
| grade1_questions = [ | |
| "Unaweza kunitambulisha nomino tano unazojua?", | |
| "Je, unajua tofauti kati ya nomino na kitendo?", | |
| "Unaweza kusema nomino tano za watu?", | |
| "Nomino zipi unazijua zinazohusiana na shule?", | |
| "Je, unaweza kusema vitendo vitano unavyofahamu?" | |
| ] | |
| grade2_questions = [ | |
| "Je, unaweza kutengeneza sentensi kwa kutumia nomino na kitendo?", | |
| "Unaweza kueleza tofauti kati ya nomino za watu na vitu?", | |
| "Je, kuna nomino zipi unazotumia kila siku?", | |
| "Unaweza kupata nomino na vitendo katika hadithi uliyosoma?" | |
| ] | |
| grade3_questions = [ | |
| "Je, unaweza kueleza jinsi ya kutumia nomino na vitendo kujenga hadithi?", | |
| "Unaweza kubainisha nomino na vitendo katika sentensi ngumu?", | |
| "Je, kuna muda unapotumia nomino au vitendo maalum?" | |
| ] | |
| if int(grade) == 1: | |
| return random.choice(grade1_questions) | |
| elif int(grade) == 2: | |
| return random.choice(grade2_questions) | |
| else: | |
| return random.choice(grade3_questions) | |
| # General Socratic templates | |
| templates = { | |
| "exploration": [ | |
| f"Unajua nini kuhusu {topic}?", | |
| f"Je, unaweza kunipa mifano ya {topic}?", | |
| f"Unafikiri nini kuhusu {topic}?", | |
| f"Je, {topic} imekuathirije maisha yako?" | |
| ], | |
| "deeper_thinking": [ | |
| f"Kwa nini unafikiri {topic} ni muhimu?", | |
| f"Je, kuna kitu kingine kinachohusiana na {topic}?", | |
| f"Unaweza kueleza {topic} kwa njia tofauti?", | |
| f"Je, {topic} hutumika vipi katika maisha ya kila siku?" | |
| ], | |
| "application": [ | |
| f"Je, unaweza kutumia {topic} kutatua shida gani?", | |
| f"Unaweza kueleza {topic} kwa rafiki yako vipi?", | |
| f"Je, kuna njia nyingine za kuelewa {topic}?", | |
| f"Unafikiri {topic} itabadilika vipi baada ya miaka kumi?" | |
| ] | |
| } | |
| # Grade-appropriate questioning | |
| if int(grade) <= 2: | |
| template_category = "exploration" | |
| elif int(grade) <= 4: | |
| template_category = "deeper_thinking" | |
| else: | |
| template_category = "application" | |
| return random.choice(templates[template_category]) | |
| # Initialize the assistant | |
| assistant = CBCLearningAssistant() | |
| def get_current_topic(grade, subject): | |
| """Get current topic based on grade and subject""" | |
| competencies = CBC_CURRICULUM.get(f"grade{grade}", {}).get(subject, []) | |
| if competencies: | |
| return random.choice(competencies) | |
| return f"{subject} concepts" | |
| def chat_interface(message, history, grade, subject): | |
| """Main chat interface function for Gradio""" | |
| if not message.strip(): | |
| return "Tafadhali share mawazo yako au uulize swali!" | |
| # Get current topic | |
| current_topic = get_current_topic(grade, subject) | |
| # Generate Socratic response | |
| response = assistant.generate_socratic_response(message, grade, subject, current_topic) | |
| return response | |
| # Custom CSS for better appearance | |
| custom_css = """ | |
| .gradio-container { | |
| font-family: 'Arial', sans-serif; | |
| max-width: 800px; | |
| margin: 0 auto; | |
| } | |
| h1 { | |
| color: #2c5aa0; | |
| text-align: center; | |
| font-size: 2em; | |
| } | |
| .gr-button { | |
| background: #4CAF50; | |
| color: white; | |
| border: none; | |
| padding: 10px 20px; | |
| border-radius: 5px; | |
| cursor: pointer; | |
| } | |
| .gr-button:hover { | |
| background: #45a049; | |
| } | |
| .chatbot { | |
| min-height: 400px; | |
| } | |
| """ | |
| # Gradio Interface | |
| with gr.Blocks(title="π CBC Socratic Learning Assistant", css=custom_css) as demo: | |
| gr.Markdown(""" | |
| # π CBC Socratic Learning Assistant | |
| ## Kenya's Competency-Based Curriculum - AI-Powered Learning | |
| Ask questions and get guided learning through Socratic questioning! | |
| """) | |
| with gr.Row(): | |
| with gr.Column(): | |
| grade = gr.Dropdown( | |
| choices=[("Grade 1", "1"), ("Grade 2", "2"), ("Grade 3", "3"), | |
| ("Grade 4", "4"), ("Grade 5", "5"), ("Grade 6", "6")], | |
| value="1", | |
| label="π Grade Level" | |
| ) | |
| with gr.Column(): | |
| subject = gr.Dropdown( | |
| choices=[("Mathematics", "Mathematics"), ("English", "English"), | |
| ("Kiswahili", "Kiswahili"), ("Science", "Science"), | |
| ("Social Studies", "Social Studies")], | |
| value="Kiswahili", | |
| label="π Subject" | |
| ) | |
| gr.Markdown("### π¬ Start Learning - Ask about what you're studying!") | |
| chatbot = gr.ChatInterface( | |
| chat_interface, | |
| additional_inputs=[grade, subject], | |
| examples=[ | |
| ["Ninajifunza Nomino na vitendo", "2", "Kiswahili"], | |
| ["Ninataka kujifunza kuhusu hesabu", "1", "Mathematics"], | |
| ["Nimesoma hadithi, nifunze zaidi", "3", "Kiswahili"], | |
| ["Ninashindwa kufahamu kuzidisha", "3", "Mathematics"] | |
| ], | |
| title="", | |
| description="" | |
| ) | |
| gr.Markdown(""" | |
| --- | |
| ### π― How to Use This Assistant: | |
| 1. Select your Grade Level and Subject | |
| 2. Tell me what you're learning about | |
| 3. I'll ask you questions to help you think deeper | |
| 4. Explore concepts through guided discovery | |
| ### π‘ Example Response: | |
| **You:** "Ninajifunza Nomino na vitendo" | |
| **Assistant:** "Unaweza kunitambulisha nomino tano unazojua?" | |
| """) | |
| if __name__ == "__main__": | |
| demo.launch() |