Spaces:
No application file
No application file
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,175 +1,151 @@
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
-
import datetime
|
| 4 |
from groq import Groq
|
| 5 |
-
from
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
|
|
|
|
|
|
|
|
|
| 10 |
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
client = Groq(api_key=GROQ_API_KEY)
|
| 12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
Do not repeat input details in body text.
|
| 36 |
-
Include only one concise header table of details.
|
| 37 |
-
|
| 38 |
-
Class: {class_}
|
| 39 |
-
Subject: {subject}
|
| 40 |
-
Topic: {topic}
|
| 41 |
-
Students: {students}
|
| 42 |
-
Duration: {duration}
|
| 43 |
-
Date: {date}
|
| 44 |
-
Teacher: {teacher}
|
| 45 |
-
"""
|
| 46 |
-
else:
|
| 47 |
-
prompt = f"""
|
| 48 |
-
آپ ایک ماہر استاد ہیں۔ درج ذیل معلومات کی بنیاد پر **BOPPPS ماڈل** کے مطابق ایک مکمل روزانہ کا تدریسی منصوبہ اردو زبان میں تیار کریں۔
|
| 49 |
-
انگریزی حروف استعمال نہ کریں، صرف اردو رسم الخط استعمال کریں۔
|
| 50 |
-
درج ذیل حصے لازمی شامل ہوں:
|
| 51 |
-
۱۔ ابتدائی تعارف (Bridge-in)
|
| 52 |
-
۲۔ ابتدائی تشخیص (Pre-Assessment)
|
| 53 |
-
۳۔ تعلیمی مقاصد (Learning Outcomes)
|
| 54 |
-
۴۔ شراکتی تعلیمی سرگرمیاں (Participatory Learning Activities)
|
| 55 |
-
۵۔ بعد از تدریس تشخیص (Post-Assessment)
|
| 56 |
-
۶۔ خلاصہ (Summary)
|
| 57 |
-
۷۔ گھریلو کام (SLOs کے مطابق)
|
| 58 |
-
|
| 59 |
-
جماعت: {class_}
|
| 60 |
-
مضمون: {subject}
|
| 61 |
-
عنوان: {topic}
|
| 62 |
-
طلباء کی تعداد: {students}
|
| 63 |
-
دورانیہ: {duration}
|
| 64 |
-
تاریخ: {date}
|
| 65 |
-
معلم: {teacher}
|
| 66 |
-
"""
|
| 67 |
-
|
| 68 |
-
# ✅ Generate text
|
| 69 |
-
response = client.chat.completions.create(
|
| 70 |
-
model=model_name,
|
| 71 |
-
messages=[{"role": "user", "content": prompt}],
|
| 72 |
-
temperature=0.7,
|
| 73 |
)
|
| 74 |
-
lesson_text = response.choices[0].message.content.strip()
|
| 75 |
-
|
| 76 |
-
# ✅ ENGLISH VERSION — create .docx
|
| 77 |
-
if language == "English":
|
| 78 |
-
doc = Document()
|
| 79 |
-
doc.add_heading("BOPPPS Lesson Plan", level=1)
|
| 80 |
-
|
| 81 |
-
table = doc.add_table(rows=7, cols=2)
|
| 82 |
-
table.style = "Table Grid"
|
| 83 |
-
headers = ["Class", "Subject", "Topic", "Students", "Duration", "Date", "Teacher"]
|
| 84 |
-
values = [class_, subject, topic, students, duration, date, teacher]
|
| 85 |
-
for i in range(7):
|
| 86 |
-
table.cell(i, 0).text = headers[i]
|
| 87 |
-
table.cell(i, 1).text = str(values[i])
|
| 88 |
-
|
| 89 |
-
doc.add_paragraph("\n" + lesson_text)
|
| 90 |
-
doc.add_paragraph("\nDeveloped by Najaf Ali Sharqi")
|
| 91 |
-
|
| 92 |
-
temp_file = NamedTemporaryFile(delete=False, suffix=".docx")
|
| 93 |
-
doc.save(temp_file.name)
|
| 94 |
-
|
| 95 |
-
final_text = f"✅ English lesson plan generated successfully for {subject} (Grade {class_})."
|
| 96 |
-
file_output = temp_file.name
|
| 97 |
-
|
| 98 |
-
# ✅ URDU VERSION — create .md
|
| 99 |
-
else:
|
| 100 |
-
urdu_md = f"""
|
| 101 |
-
<div dir="rtl" align="right">
|
| 102 |
-
|
| 103 |
-
# یومیہ تدریسی منصوبہ (BOPPPS ماڈل)
|
| 104 |
-
|
| 105 |
-
| کلیدی معلومات | تفصیل |
|
| 106 |
-
|----------------|--------|
|
| 107 |
-
| جماعت | {class_} |
|
| 108 |
-
| مضمون | {subject} |
|
| 109 |
-
| عنوان | {topic} |
|
| 110 |
-
| طلباء کی تعداد | {students} |
|
| 111 |
-
| دورانیہ | {duration} |
|
| 112 |
-
| تاریخ | {date} |
|
| 113 |
-
| معلم | {teacher} |
|
| 114 |
-
|
| 115 |
-
---
|
| 116 |
-
|
| 117 |
-
{lesson_text}
|
| 118 |
-
|
| 119 |
-
---
|
| 120 |
-
|
| 121 |
-
**مرتب کردہ: نجف علی شرقی**
|
| 122 |
-
</div>
|
| 123 |
-
"""
|
| 124 |
-
temp_file = NamedTemporaryFile(delete=False, suffix=".md", mode="w", encoding="utf-8")
|
| 125 |
-
temp_file.write(urdu_md)
|
| 126 |
-
temp_file.close()
|
| 127 |
-
|
| 128 |
-
final_text = f"✅ اردو تدریسی منصوبہ برائے مضمون {subject} کامیابی سے تیار ہو گیا۔"
|
| 129 |
-
file_output = temp_file.name
|
| 130 |
-
|
| 131 |
-
# ✅ Theme customization (brightness)
|
| 132 |
-
if theme == "Dark":
|
| 133 |
-
theme_css = "background-color:#111;color:#fff;padding:10px;border-radius:10px;"
|
| 134 |
-
else:
|
| 135 |
-
theme_css = "background-color:#fdfdfd;color:#000;padding:10px;border-radius:10px;"
|
| 136 |
-
|
| 137 |
-
safe_html = final_text.replace("\n", "<br>")
|
| 138 |
-
display_html = f"<div style='{theme_css}'>{safe_html}</div>"
|
| 139 |
-
|
| 140 |
-
return display_html, file_output
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
# ✅ Dropdowns and Interface
|
| 144 |
-
demo = gr.Interface(
|
| 145 |
-
fn=generate_lesson_plan,
|
| 146 |
-
inputs=[
|
| 147 |
-
gr.Radio(["English", "Urdu"], label="Select Language / زبان کا انتخاب"),
|
| 148 |
-
gr.Dropdown([f"Grade {i}" for i in range(1, 17)], label="Class / جماعت"),
|
| 149 |
-
gr.Dropdown(
|
| 150 |
-
["Urdu", "English", "Arabic", "Science", "Mathematics", "Biology",
|
| 151 |
-
"Chemistry", "Physics", "Zoology", "Botany", "Civics", "Islamiat"],
|
| 152 |
-
label="Subject / مضمون"
|
| 153 |
-
),
|
| 154 |
-
gr.Textbox(label="Topic / عنوان"),
|
| 155 |
-
gr.Slider(1, 200, value=30, step=1, label="Number of Students / طلباء کی تعداد"),
|
| 156 |
-
gr.Slider(30, 60, value=40, step=5, label="Duration (minutes) / دورانیہ (منٹ)"),
|
| 157 |
-
gr.Textbox(label="Date / تاریخ", value=str(datetime.date.today())),
|
| 158 |
-
gr.Textbox(label="Teacher Name / معلم کا نام"),
|
| 159 |
-
gr.Radio(["Light", "Dark"], label="Theme / پس منظر کا انتخاب", value="Light"),
|
| 160 |
-
],
|
| 161 |
-
outputs=[
|
| 162 |
-
gr.HTML(label="📄 Lesson Plan Preview"),
|
| 163 |
-
gr.File(label="⬇️ Download File (.docx or .md)")
|
| 164 |
-
],
|
| 165 |
-
title="📘 AI BOPPPS Lesson Plan Generator (Urdu + English)",
|
| 166 |
-
description=(
|
| 167 |
-
"⚙️ Developed by **Najaf Ali Sharqi**. <br>"
|
| 168 |
-
"یہ ایپ خودکار طور پر اردو یا انگریزی میں مکمل BOPPPS ماڈل کے مطابق یومیہ تدریسی منصوبہ تیار کرتی ہے۔<br>"
|
| 169 |
-
"اردو ورژن `.md` فارمیٹ میں جبکہ انگریزی ورژن `.docx` میں ڈاؤن لوڈ ہوتا ہے۔"
|
| 170 |
-
),
|
| 171 |
-
theme="default"
|
| 172 |
-
)
|
| 173 |
-
|
| 174 |
-
demo.launch()
|
| 175 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
|
|
|
| 3 |
from groq import Groq
|
| 4 |
+
from gtts import gTTS
|
| 5 |
+
import tempfile
|
| 6 |
+
import re
|
| 7 |
+
import traceback
|
| 8 |
+
|
| 9 |
+
# ==================================
|
| 10 |
+
# ✅ Configuration
|
| 11 |
+
# ==================================
|
| 12 |
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
|
| 13 |
+
|
| 14 |
+
if not GROQ_API_KEY:
|
| 15 |
+
raise ValueError("Please set the environment variable GROQ_API_KEY.")
|
| 16 |
+
|
| 17 |
client = Groq(api_key=GROQ_API_KEY)
|
| 18 |
|
| 19 |
+
# ==================================
|
| 20 |
+
# ✅ Utility: Clean and format text
|
| 21 |
+
# ==================================
|
| 22 |
+
def clean_text(text):
|
| 23 |
+
"""Remove special characters and clean spacing."""
|
| 24 |
+
text = re.sub(r"[^a-zA-Z0-9\u0600-\u06FF\s.,?!]", "", text) # keep Urdu/English + punctuation
|
| 25 |
+
text = re.sub(r"\s+", " ", text).strip()
|
| 26 |
+
return text
|
| 27 |
+
|
| 28 |
+
# ==================================
|
| 29 |
+
# ✅ Step 1 — Speech to Text (Urdu + English Auto)
|
| 30 |
+
# ==================================
|
| 31 |
+
def speech_to_text(audio_path):
|
| 32 |
+
"""Transcribe Urdu or English speech using Groq Whisper."""
|
| 33 |
+
try:
|
| 34 |
+
with open(audio_path, "rb") as file:
|
| 35 |
+
transcription = client.audio.transcriptions.create(
|
| 36 |
+
file=(audio_path, file.read()),
|
| 37 |
+
model="whisper-large-v3",
|
| 38 |
+
response_format="verbose_json",
|
| 39 |
+
language="auto" # 👈 Auto-detect Urdu or English
|
| 40 |
+
)
|
| 41 |
+
text = transcription.text.strip()
|
| 42 |
+
if not text:
|
| 43 |
+
text = "میں آپ کی آواز سمجھ نہیں سکا۔ براہ کرم دوبارہ بولیں۔"
|
| 44 |
+
return clean_text(text)
|
| 45 |
+
except Exception as e:
|
| 46 |
+
print("Transcription Error:", traceback.format_exc())
|
| 47 |
+
return "I could not understand your voice. Please try again."
|
| 48 |
+
|
| 49 |
+
# ==================================
|
| 50 |
+
# ✅ Step 2 — Get AI Response (Text → Text)
|
| 51 |
+
# ==================================
|
| 52 |
+
def ai_response(user_text):
|
| 53 |
+
"""Generate AI response with correct grammar and punctuation."""
|
| 54 |
+
try:
|
| 55 |
+
completion = client.chat.completions.create(
|
| 56 |
+
model="openai/gpt-oss-120b",
|
| 57 |
+
messages=[
|
| 58 |
+
{"role": "system", "content": "You are a helpful assistant. Reply in the same language as the user's question. Use correct grammar and punctuation without emojis or special symbols."},
|
| 59 |
+
{"role": "user", "content": user_text}
|
| 60 |
+
],
|
| 61 |
+
temperature=0.6,
|
| 62 |
+
max_completion_tokens=512,
|
| 63 |
+
top_p=1,
|
| 64 |
+
stream=False
|
| 65 |
+
)
|
| 66 |
+
reply = completion.choices[0].message.content.strip()
|
| 67 |
+
return clean_text(reply)
|
| 68 |
+
except Exception as e:
|
| 69 |
+
print("AI Response Error:", traceback.format_exc())
|
| 70 |
+
return "Sorry, I could not generate an answer."
|
| 71 |
+
|
| 72 |
+
# ==================================
|
| 73 |
+
# ✅ Step 3 — Text to Speech (Answer → Audio)
|
| 74 |
+
# ==================================
|
| 75 |
+
def text_to_speech(text):
|
| 76 |
+
"""Convert Urdu or English text into spoken audio file."""
|
| 77 |
+
try:
|
| 78 |
+
lang = "ur" if any('\u0600' <= c <= '\u06FF' for c in text) else "en"
|
| 79 |
+
tts = gTTS(text=text, lang=lang, slow=False)
|
| 80 |
+
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
|
| 81 |
+
tts.save(temp_file.name)
|
| 82 |
+
return temp_file.name
|
| 83 |
+
except Exception as e:
|
| 84 |
+
print("TTS Error:", traceback.format_exc())
|
| 85 |
+
return None
|
| 86 |
+
|
| 87 |
+
# ==================================
|
| 88 |
+
# ✅ Step 4 — Full Assistant Logic
|
| 89 |
+
# ==================================
|
| 90 |
+
def assistant(audio):
|
| 91 |
+
"""Full pipeline: Audio → Text → AI → Voice."""
|
| 92 |
+
if audio is None:
|
| 93 |
+
return "No audio detected. Please record again.", "", None, None
|
| 94 |
+
|
| 95 |
+
# 1️⃣ Speech to Text
|
| 96 |
+
user_text = speech_to_text(audio)
|
| 97 |
+
print(f"🎙️ Recognized: {user_text}")
|
| 98 |
+
|
| 99 |
+
# 2️⃣ AI Response
|
| 100 |
+
ai_text = ai_response(user_text)
|
| 101 |
+
print(f"💬 AI Answer: {ai_text}")
|
| 102 |
+
|
| 103 |
+
# 3️⃣ Text to Speech
|
| 104 |
+
voice_output = text_to_speech(ai_text)
|
| 105 |
+
if not voice_output:
|
| 106 |
+
return user_text, ai_text, None, None
|
| 107 |
+
|
| 108 |
+
# 4️⃣ Provide download link
|
| 109 |
+
return user_text, ai_text, voice_output, voice_output
|
| 110 |
+
|
| 111 |
+
# ==================================
|
| 112 |
+
# ✅ Step 5 — Gradio Interface
|
| 113 |
+
# ==================================
|
| 114 |
+
with gr.Blocks(title="AI Voice Assistant for Blind Users") as demo:
|
| 115 |
+
gr.Markdown("## 🧠 AI Voice Assistant for Blind Users (Urdu + English)")
|
| 116 |
+
gr.Markdown(
|
| 117 |
+
"""
|
| 118 |
+
🎤 **Speak your question in Urdu or English** —
|
| 119 |
+
The assistant will automatically understand, reply with correct grammar and punctuation,
|
| 120 |
+
and speak the answer aloud. You can also download the spoken answer below.
|
| 121 |
+
"""
|
| 122 |
+
)
|
| 123 |
|
| 124 |
+
with gr.Row():
|
| 125 |
+
audio_input = gr.Audio(
|
| 126 |
+
sources=["microphone"],
|
| 127 |
+
type="filepath",
|
| 128 |
+
label="🎙️ Speak Now"
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
with gr.Row():
|
| 132 |
+
recognized_text = gr.Textbox(label="🗣️ Recognized Question (Text)")
|
| 133 |
+
with gr.Row():
|
| 134 |
+
ai_answer = gr.Textbox(label="💬 AI Answer (Text)")
|
| 135 |
+
with gr.Row():
|
| 136 |
+
audio_output = gr.Audio(label="🔊 AI Voice Response")
|
| 137 |
+
with gr.Row():
|
| 138 |
+
download_link = gr.File(label="⬇️ Download Answer Voice Note")
|
| 139 |
+
|
| 140 |
+
# Auto process when audio recorded
|
| 141 |
+
audio_input.change(
|
| 142 |
+
assistant,
|
| 143 |
+
inputs=[audio_input],
|
| 144 |
+
outputs=[recognized_text, ai_answer, audio_output, download_link],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
|
| 147 |
+
# ==================================
|
| 148 |
+
# ✅ Step 6 — Launch App
|
| 149 |
+
# ==================================
|
| 150 |
+
if __name__ == "__main__":
|
| 151 |
+
demo.launch()
|