File size: 4,509 Bytes
38e4bf1
 
 
 
 
 
 
c5c3a85
38e4bf1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import requests
import gradio as gr
from gtts import gTTS
import tempfile

# Get API key from Hugging Face Secrets (Settings β†’ Repository secrets)
groq_api_key = os.getenv("groq")

# API endpoint and headers
url = "https://api.groq.com/openai/v1/chat/completions"
headers = {"Authorization": f"Bearer {groq_api_key}"}

# Main function with smart prompting
def chat_with_groq(user_input, mode, grade_level):
    if not user_input.strip():
        return "❗ Please enter a sentence.", None

    grade_int = int(grade_level)
    if grade_int <= 2:
        paragraph_lines = 1
        level_prompt = "Use very simple and beginner-friendly Arabic words suitable for a small child in early primary school.\n"
    elif grade_int <= 6:
        paragraph_lines = 3
        level_prompt = "Use clear and moderately simple Arabic that suits an elementary school student.\n"
    elif grade_int <= 9:
        paragraph_lines = 5
        level_prompt = "Use slightly advanced Arabic suited for a middle school student. Make the sentence structure a bit richer.\n"
    else:
        paragraph_lines = 8
        level_prompt = "Use rich and expressive Arabic suitable for high school students. Use more complex grammar and vocabulary.\n"

    # Mode-specific prompting
    if mode == "Translate Arabic ➜ English":
        prompt = level_prompt + f"Translate this Arabic sentence to English. Just give the clean translation:\n{user_input}"
    elif mode == "Translate English ➜ Arabic":
        prompt = level_prompt + f"Translate this English sentence into Modern Standard Arabic. Just give the Arabic sentence:\n{user_input}"
    elif mode == "Explain Arabic Grammar":
        prompt = level_prompt + f"Explain the grammar of this Arabic sentence simply and clearly:\n{user_input}"
    elif mode == "Check My Arabic Sentence":
        prompt = level_prompt + f"Check if this Arabic sentence is grammatically correct. If not, fix it and explain briefly:\n{user_input}"
    elif mode == "Make Sentence using a Word":
        prompt = level_prompt + f"Create 1 sentence in Modern Standard Arabic using the word '{user_input}'. Only respond in Arabic without translation or explanation."
    elif mode == "Make Paragraph using a Word":
        prompt = level_prompt + f"Write a paragraph in Modern Standard Arabic using the word '{user_input}', about {paragraph_lines} lines long. Only respond in Arabic without translation or explanation."
    else:
        prompt = user_input

    body = {
        "model": "llama-3.1-8b-instant",
        "messages": [{"role": "user", "content": prompt}]
    }

    response = requests.post(url, headers=headers, json=body)

    if response.status_code == 200:
        result = response.json()['choices'][0]['message']['content']

        # TTS for Arabic modes
        if mode in ["Translate English ➜ Arabic", "Make Sentence using a Word", "Make Paragraph using a Word"]:
            try:
                tts = gTTS(text=result, lang="ar")
                with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as fp:
                    tts.save(fp.name)
                    return result, fp.name
            except:
                return result + "\n\n(Note: Could not generate audio)", None
        else:
            return result, None
    else:
        return f"❌ Error: {response.json()}", None

# Gradio UI
interface = gr.Interface(
    fn=chat_with_groq,
    inputs=[
        gr.Textbox(lines=3, placeholder="Enter a word or sentence in Arabic or English..."),
        gr.Dropdown(
            choices=[
                "Translate Arabic ➜ English",
                "Translate English ➜ Arabic",
                "Explain Arabic Grammar",
                "Check My Arabic Sentence",
                "Make Sentence using a Word",
                "Make Paragraph using a Word"
            ],
            label="Select Mode",
            value="Translate Arabic ➜ English"
        ),
        gr.Dropdown(
            choices=[str(i) for i in range(1, 13)],
            label="Select Grade Level",
            value="5"
        )
    ],
    outputs=[
        gr.Textbox(label="πŸ“˜ Response"),
        gr.Audio(label="πŸ”Š Arabic Pronunciation (if applicable)")
    ],
    title="πŸ“š Arabic Study Assistant (Groq + LLaMA 3.1 8B)",
    description="🧠 Built to help students and parents learn Arabic β€” grammar, translation, writing practice, and pronunciation! Grade-level support included."
)

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