'
)
def loading_state(pesan: str = "CodeBot sedang berpikir...") -> str:
"""Generate loading state dengan CodeBot mascot."""
return (
f'
'
f'
'
f'
🤖
'
f'
'
f'
'
f'
{pesan}
'
f'
'
)
def panel(icon: str, title: str, body: str) -> str:
"""Uniform panel wrapper used in every split-column layout."""
return (
f'
'
f'
{icon}
{title}
'
f'
{body}
'
f'
'
)
# ============================================================================ #
# Demo Mode Handlers #
# ============================================================================ #
def demo_load_ocr():
"""Load demo image untuk OCR tab."""
demo_img_path = get_demo_image_path()
if not demo_img_path:
return None, alert(
"error",
"Demo image tidak ditemukan. Letakkan berkas di frontend/assets/demo_handwriting.jpg",
)
return demo_img_path, alert("info", DEMO_INFO_MESSAGE)
def demo_load_tutor_error():
"""Load demo code dengan error untuk AI Tutor."""
return (
DEMO_TUTOR["code_with_error"],
DEMO_TUTOR["student_id"],
DEMO_TUTOR["level"],
DEMO_TUTOR["exercise_id"],
alert("info", DEMO_INFO_MESSAGE + " Kode ini punya error yang perlu diperbaiki.")
)
def demo_load_tutor_success():
"""Load demo code tanpa error untuk AI Tutor."""
return (
DEMO_TUTOR["code_success"],
DEMO_TUTOR["student_id"],
DEMO_TUTOR["level"],
DEMO_TUTOR["exercise_id"],
alert("success", DEMO_INFO_MESSAGE + " Kode ini sudah benar!")
)
def demo_load_voice_tts():
"""Load demo text untuk TTS."""
return DEMO_VOICE["tts_text"], DEMO_VOICE["gender"], alert("info", DEMO_INFO_MESSAGE)
def demo_load_exercise():
"""Load demo topic untuk generate exercise."""
return (
DEMO_EXERCISE["topic"],
DEMO_EXERCISE["difficulty"],
alert("info", DEMO_INFO_MESSAGE + " Klik 'Buat!' untuk generate latihan AI.")
)
def demo_load_student():
"""Load demo data siswa untuk registrasi."""
return (
DEMO_STUDENT["register"]["name"],
DEMO_STUDENT["register"]["age"],
DEMO_STUDENT["register"]["level"],
alert("info", DEMO_INFO_MESSAGE)
)
def demo_load_progress():
"""Load demo student ID untuk cek progress."""
return DEMO_STUDENT["progress_student_id"], alert("info", DEMO_INFO_MESSAGE + " Klik 'Lihat Progress' untuk melihat data siswa.")
# ============================================================================ #
# Handlers #
# ============================================================================ #
def h_ocr(image):
if not image:
return "", alert("info", "Please upload or take a photo of handwritten Python code first.")
with open(image, "rb") as f:
raw = f.read()
try:
d = run(_post("/api/ocr/extract", files={"berkas": ("photo.jpg", raw, "image/jpeg")}))
conf = d.get("confidence", 0)
pct = int(conf * 100)
bar = (
f'
'
f'
AI Confidence{pct}%
'
f'
'
f'
'
)
if _SPACE_DEMO:
pesan_sukses = f"Hasil OCR demo Bahasa Indonesia siap.{bar}"
else:
pesan_sukses = f"Vision AI successfully extracted the code!{bar}"
return d.get("code", ""), alert("success", pesan_sukses)
except Exception as e:
return "", alert("error", f"Failed to process image: {str(e)[:200]}")
def h_tutor(code, sid_str, level, ex_id, lang_label):
if not code.strip():
return "", "", "", alert("info", "Please enter your Python code in the editor on the left.")
bhs = lang_code(lang_label)
sid = int(sid_str) if sid_str.strip().isdigit() else 1
try:
d = run(_post("/api/agent/tutor", json={
"code": code, "student_id": sid,
"student_level": level, "exercise_id": ex_id or None, "bahasa": bhs,
}))
final = d.get("final_result", "")
attempts = d.get("attempts", [])
exec_out = next((a.get("output", "") for a in attempts if a.get("stage") == "execution"), "")
fb = next((a["ai_feedback"] for a in reversed(attempts) if a.get("ai_feedback")), {})
status_map = {
"success": ("success", "🎉 Code ran perfectly — great work!"),
"syntax_error": ("error", "📝 Syntax error found — let's fix it together!"),
"runtime_error": ("warning", "⚡ Runtime error — check the output for details."),
"timeout": ("error", "⏱️ Code timed out — there may be an infinite loop."),
}
t, msg = status_map.get(final, ("info", final))
status_h = alert(t, msg)
md = ""
if fb.get("encouragement"):
md += f'
{fb["encouragement"]}
\n\n'
if fb.get("understanding"):
md += f"**🧠 About this code:**\n\n{fb['understanding']}\n\n"
errors = fb.get("errors", [])
if errors:
md += "**🔍 Issues found:**\n\n"
for e in errors:
ln = f"Line {e['line']}: " if e.get("line") else ""
md += f"- 🔴 **{ln}**{e.get('explanation', '')}\n"
if e.get("fix"):
md += f" - 💡 _{e['fix']}_\n"
md += "\n"
sug = fb.get("suggestions", [])
if sug:
md += "**✨ Tutor tips:**\n\n" + "".join(f"- {s}\n" for s in sug)
fixed = fb.get("corrected_code", "") or "# Your code is already correct! 🎉"
return exec_out or "(no output)", md, fixed, status_h
except Exception as e:
return "", "", "", alert("error", f"Request failed: {str(e)[:250]}")
def h_hint(code, err_msg, lvl, lang_label):
if not code.strip():
return alert("info", "Please enter your code in the AI Tutor tab first.")
try:
d = run(_post("/api/agent/hint", json={
"code": code, "error": err_msg or "-",
"hint_level": int(lvl), "student_level": "beginner",
}))
hint = d.get("hint", "")
labels = {1: ("🌱", "Guiding Question"), 2: ("🔍", "Error Location"), 3: ("🎯", "Full Solution")}
icon, title = labels.get(int(lvl), ("💡", "Hint"))
return (
f'
'
f'
'
f'{icon}'
f'Level {int(lvl)} — {title}'
f'
'
f'
{hint}
'
f'
'
)
except Exception as e:
return alert("error", f"Request failed: {str(e)[:200]}")
def h_voice_ask(audio_path, lang_label, level):
"""Generator agar Gradio bisa tampil status loading sambil menunggu proses panjang."""
path_audio = audio_path
if isinstance(audio_path, dict):
# Gradio kadang mengirim struktur berisi path file
path_audio = (
audio_path.get("path")
or audio_path.get("name")
or audio_path.get("file")
)
if not path_audio or (isinstance(path_audio, str) and not path_audio.strip()):
yield None, alert("info", "Rekam pertanyaanmu dulu menggunakan mikrofon, lalu tekan Kirim.")
return
bhs = lang_code(lang_label)
# Tampilkan status loading segera agar UI tidak terasa beku
if _SPACE_DEMO:
catatan_proses = (
"Jawaban demo Bahasa Indonesia — tanpa Whisper, Gemma, atau TTS"
)
else:
catatan_proses = (
"Whisper STT → Gemma AI → TTS — butuh 15–60 detik"
)
yield None, (
'
'
'
'
'
🎤
'
'
'
'
'
'
CodeBot sedang mendengarkan & berpikir... '
f'{catatan_proses}
'
'
'
)
try:
with open(path_audio, "rb") as berkas_suara:
isi_audio = berkas_suara.read()
isi_respons, header_respons = run(_post_raw(
"/api/audio/ask",
files={"berkas": ("q.wav", isi_audio, "audio/wav")},
params={"bahasa": bhs, "student_level": level},
))
import tempfile
path_output = tempfile.mktemp(suffix=".mp3")
with open(path_output, "wb") as berkas_output:
berkas_output.write(isi_respons)
teks_pertanyaan = header_respons.get("x-pertanyaan", "...")
teks_jawaban = header_respons.get("x-jawaban", "...")
info_html = (
f'
'
f'{alert("info", f"Pertanyaan kamu: {teks_pertanyaan}")}'
f'{alert("success", f"CodeBot menjawab: {teks_jawaban}")}'
f'
'
)
yield path_output, info_html
except httpx.HTTPStatusError as kesalahan_httpx:
pesan_detail = ""
try:
isi_json = kesalahan_httpx.response.json()
if isinstance(isi_json, dict) and "detail" in isi_json:
pesan_detail = str(isi_json["detail"])
else:
pesan_detail = str(isi_json)
except Exception:
pesan_detail = (kesalahan_httpx.response.text or str(kesalahan_httpx))[:400]
yield None, alert("error", f"Request gagal: {pesan_detail}")
except Exception as kesalahan_umum:
yield None, alert("error", f"Request gagal: {str(kesalahan_umum)[:200]}")
def h_tts(text, lang_label, gender):
if not text.strip():
return None, alert("info", "Please enter the text you want to be read aloud.")
try:
content, headers = run(_post_raw("/api/audio/tts", json={
"teks": text, "bahasa": lang_code(lang_label), "gender": gender,
}))
import tempfile
out = tempfile.mktemp(suffix=".mp3")
with open(out, "wb") as f:
f.write(content)
catatan = (headers or {}).get("x-demo-catatan")
if catatan:
return out, alert("info", catatan)
return out, alert("success", "Audio ready — press ▶ to play.")
except Exception as e:
return None, alert("error", f"TTS failed: {str(e)[:200]}")
def h_exercise_list(diff):
try:
params = {} if diff == "All" else {"difficulty": diff.lower()}
d = run(_get("/api/exercises/", params=params))
items = d.get("latihan", [])
if not items:
return alert("info", "No exercises found for this filter.")
lp = {"beginner": "cb-lp-b", "intermediate": "cb-lp-i", "advanced": "cb-lp-a"}
html = '
'
for i in items:
lvl = i.get("difficulty", "beginner")
cls = lp.get(lvl, "cb-lp-b")
judul = i["judul"]
desc = i["ringkas"]
kode = i["starter_code"]
eid = i["exercise_id"]
html += (
f'
'
f'
'
f'{judul}'
f'{lvl}'
f'
'
f'
{desc}
'
f'
{kode}
'
f'
'
f'ID: {eid}'
f'
'
f'
'
)
return html + '
'
except Exception as e:
return alert("error", f"Failed to load exercises: {e}")
def h_generate_exercise(topic, diff, lang_label):
if not topic.strip():
return "", "", "", alert("info", "Enter an exercise topic first.")
try:
d = run(_post("/api/exercises/generate", json={
"topic": topic, "difficulty": diff.lower(), "bahasa": lang_code(lang_label),
}))
if "error" in d:
return "", "", "", alert("error", "AI failed to generate an exercise. Please try again.")
title = d.get("title", "")
return (
title, d.get("instructions", ""), d.get("starter_code", ""),
alert("success", f"Exercise {title} created successfully!"),
)
except Exception as e:
return "", "", "", alert("error", f"Request failed: {e}")
def h_latihan_cek(kode_siswa, instruksi_latihan, level, lang_label):
"""Jalankan kode latihan dan minta feedback AI — mirip tab AI Tutor."""
if not kode_siswa.strip():
return "", "", alert("warning", "Tulis atau edit kode di editor dulu, baru tekan Jalankan & Cek.")
bhs = lang_code(lang_label)
try:
hasil_tutor = run(_post("/api/agent/tutor", json={
"code": kode_siswa,
"student_id": 1,
"student_level": level,
"exercise_id": None,
"bahasa": bhs,
# Sertakan instruksi latihan sebagai konteks tambahan agar AI tahu
# tujuan latihan saat memberikan feedback
"context": instruksi_latihan or "",
}))
status_akhir = hasil_tutor.get("final_result", "")
daftar_percobaan = hasil_tutor.get("attempts", [])
# Ambil output eksekusi
keluaran_kode = next(
(p.get("output", "") for p in daftar_percobaan if p.get("stage") == "execution"),
"",
)
# Ambil feedback AI dari percobaan terakhir yang punya feedback
umpan_balik = next(
(p["ai_feedback"] for p in reversed(daftar_percobaan) if p.get("ai_feedback")),
{},
)
peta_status = {
"success": ("success", "Kode berhasil dijalankan dengan benar!"),
"syntax_error": ("error", "Ada kesalahan sintaks — yuk perbaiki bersama!"),
"runtime_error": ("warning", "Ada error saat dijalankan — cek output di bawah."),
"timeout": ("error", "Kode berjalan terlalu lama — mungkin ada loop tak berujung."),
}
tipe_alert, pesan_alert = peta_status.get(status_akhir, ("info", status_akhir))
html_status = alert(tipe_alert, pesan_alert)
# Susun markdown feedback
teks_feedback = ""
if umpan_balik.get("encouragement"):
teks_feedback += f'
{umpan_balik["encouragement"]}
\n\n'
if umpan_balik.get("understanding"):
teks_feedback += f"**Penjelasan kode:**\n\n{umpan_balik['understanding']}\n\n"
daftar_error = umpan_balik.get("errors", [])
if daftar_error:
teks_feedback += "**Masalah yang ditemukan:**\n\n"
for err in daftar_error:
nomor_baris = f"Baris {err['line']}: " if err.get("line") else ""
teks_feedback += f"- {nomor_baris}{err.get('explanation', '')}\n"
if err.get("fix"):
teks_feedback += f" - Saran: _{err['fix']}_\n"
teks_feedback += "\n"
daftar_saran = umpan_balik.get("suggestions", [])
if daftar_saran:
teks_feedback += "**Tips dari CodeBot:**\n\n" + "".join(f"- {s}\n" for s in daftar_saran)
kode_perbaikan = umpan_balik.get("corrected_code", "") or ""
return keluaran_kode or "(tidak ada output)", teks_feedback, html_status
except Exception as kesalahan:
return "", "", alert("error", f"Request gagal: {str(kesalahan)[:250]}")
def h_register_student(name, age, level):
if not name.strip():
return alert("warning", "Student name cannot be empty.")
try:
d = run(_post("/api/students/", json={
"name": name, "age": int(age) if age.isdigit() else None, "level": level,
}))
lvl_bg = {"beginner": "#D1FAE5", "intermediate": "#FEF3C7", "advanced": "#FEE2E2"}.get(d["level"], "#EEF2FF")
return (
f'
'
f'{alert("success", "Student registered successfully! Save the ID below.")}'
f'
'
f'
🎓
'
f'
'
f'
{d["name"]}
'
f'
'
f'ID #{d["id"]}'
f'{d["level"]}'
f'
'
f'
'
f'
'
f'
'
)
except Exception as e:
return alert("error", f"Registration failed: {e}")
def h_progress(sid_str):
if not sid_str.strip().isdigit():
return alert("warning", "Please enter a numeric student ID.")
try:
d = run(_get(f"/api/students/{sid_str}/progress"))
name = d.get("nama", "?")
level = d.get("level", "?")
done = d.get("total_selesai", 0)
avg = d.get("rata_rata_skor")
courses = d.get("latihan", [])
total = len(courses)
pct = int(done / total * 100) if total > 0 else 0
avg_str = f"{avg:.0f}" if avg is not None else "—"
badge = "🏆" if done >= 3 else ("⭐" if done >= 1 else "🌱")
rows = ""
for item in courses:
is_done = item["completed"]
cls = "done" if is_done else "ongoing"
score = f"{item['avg_score']:.0f}" if item.get("avg_score") is not None else "—"
rows += (
f'
'
f'
'
f'{"✅" if is_done else "🔄"}'
f'
'
f'
{item["exercise_id"]}
'
f'
{item["attempts"]} attempt(s)
'
f'
'
f'
'
f'
'
f'
{score}
'
f'
score
'
f'
'
f'
'
)
if not rows:
rows = alert("info", "No exercises attempted yet. Get started!")
return (
f'
'
# Profile card
f'
'
f'
{badge}
'
f'
'
f'
{name}
'
f'
'
f'Level: {level}
'
f'
'
f'
'
f'Overall Progress{pct}%
'
f'
'
f'
'
f'
'
f'
'
# Stats
f'
'
f'
{done}
Completed
'
f'
{avg_str}
Avg Score
'
f'
{total}
Attempted
'
f'
{pct}%
Completion
'
f'
'
# Exercise list
f'
'
f'
Exercise Progress
'
f'{rows}'
f'
'
f'
'
)
except httpx.HTTPStatusError as e:
msg = "Student not found. Check the ID." if e.response.status_code == 404 else str(e)
return alert("error", msg)
except Exception as e:
return alert("error", f"Request failed: {e}")
def h_dashboard():
try:
d = run(_get("/api/teacher/dashboard"))
r = d.get("ringkasan", {})
dist = d.get("distribusi_level", {})
pop = d.get("latihan_populer", [])
stuck= d.get("siswa_stuck", [])
errs = d.get("top_errors", [])
sr = r.get("success_rate_persen", 0)
# Warna per level untuk distribusi
warna_level = {"beginner": "#10B981", "intermediate": "#F59E0B", "advanced": "#8B5CF6"}
dist_html = "".join(
f'
'
f'
{v}
'
f'
{k.capitalize()}
'
f'
'
for k, v in dist.items()
)
col = max(1, len(dist))
# Popular exercises bar chart
max_att = max((p["total_attempts"] for p in pop), default=1)
pop_html = ""
for p in pop[:5]:
pct = int(p["total_attempts"] / max_att * 100)
pop_html += (
f'
'
f'
'
f'{p["exercise_id"]}'
f'{p["total_attempts"]}×'
f'
'
f'
'
f'
'
)
if not pop_html:
pop_html = f'
No data yet.
'
# Stuck students
stuck_html = "".join(
f'
'
f'
'
f'⚠️'
f'
'
f'
{s["nama"]}
'
f'
stuck on {s["exercise_id"]}
'
f'
'
f'
'
f'{s["attempts"]}×'
f'
'
for s in stuck[:5]
) or alert("success", "No students are currently stuck! 🎉")
# Top errors
err_html = ""
for e in errs:
err_html += (
f'
'
f'{e["type"]}'
f'{e["count"]}×'
f'
'
)
if not err_html:
err_html = f'
No error data yet.
'
# Warna per metrik — pakai inline style agar selalu terlihat
# meski CSS variable belum load di konteks gr.HTML()
gaya_stat = (
"border-radius:0.625rem;padding:24px 20px;text-align:center;"
"background:#FFFFFF;border:1px solid #E2E8F0;"
"box-shadow:0 2px 8px rgba(0,0,0,0.06);"
)
gaya_nilai = (
"font-size:2.4rem;font-weight:800;line-height:1;"
"letter-spacing:-0.02em;margin-bottom:6px;"
)
gaya_label = (
"font-size:0.78rem;font-weight:600;color:#64748B;"
"text-transform:uppercase;letter-spacing:0.05em;"
)
gaya_kartu = (
"background:#FFFFFF;border:1px solid #E2E8F0;"
"border-radius:0.625rem;padding:20px;"
)
gaya_judul_kartu = (
"font-weight:700;font-size:0.95rem;color:#1E293B;"
"margin-bottom:14px;display:block;"
)
def kotak_stat(nilai, label, warna):
return (
f'
'
# Baris 2 — Distribusi level + Latihan populer
f'
'
f'
'
f'Level Siswa'
f'
{dist_html}
'
f'
'
f'
'
f'Latihan Paling Banyak Dicoba'
f'{pop_html}'
f'
'
f'
'
# Baris 3 — Siswa butuh bantuan + Error terbanyak
f'
'
f'
'
f'⚠️ Siswa Butuh Bantuan'
f'{stuck_html}'
f'
'
f'
'
f'❌ Error Paling Sering'
f'{err_html}'
f'
'
f'
'
f'
'
)
except Exception as e:
return alert("error", f"Failed to load dashboard: {e}")
def h_insight():
try:
d = run(_get("/api/teacher/insights"))
ai = d.get("ai_insight", {})
sarans = ""
for idx, s in enumerate(ai.get("saran_pengajaran", []), 1):
sarans += (
f'
'
f'
{idx}
'
f'
{s}
'
f'
'
)
return (
f'
'
f'
'
f'
📋
'
f'
Class Overview
'
f'
{ai.get("kondisi_kelas","—")}
'
f'
'
f'
'
f'
🎯
'
f'
Topics Needing Attention
'
f'
{ai.get("topik_perhatian","—")}
'
f'
'
f'
'
f'
💡 Recommendations for Next Class
'
f'{sarans or alert("info","Click the button above to generate AI insight.")}'
f'
'
f'
'
f'
🆘
'
f'
Students Requiring Special Attention
'
f'
{ai.get("siswa_butuh_bantuan","—")}
'
f'
'
f'
'
)
except Exception as e:
return alert("error", f"Request failed: {e}")
# ============================================================================ #
# UI Layout #
# ============================================================================ #
with gr.Blocks(title="CodeBuddy — AI Coding Tutor") as demo:
# ── HERO ──────────────────────────────────────────────────────────────── #
gr.HTML(f"""
🤖
CodeBuddy
Asisten AI Belajar Coding Pintar
🤖 AI-Powered🌍 5 Bahasa Daerah📸 OCR Tulisan Tangan
{"" if _SPACE_DEMO else '🔒 100% Offline'}
🎤 Mode Suara👨🏫 Dashboard Guru
📸
Vision OCR
Ekstrak kode langsung dari foto tulisan tangan dengan akurasi tinggi
🤖
Agentic Tutoring
Pipeline 4 tahap lengkap: syntax → eksekusi → analisis → feedback AI
🎤
Mode Suara
Tanya jawab interaktif dengan suara untuk pengalaman belajar yang mudah
🌍
Bahasa Daerah
Mendukung 5 bahasa daerah untuk jangkauan inklusif se-Indonesia
""")
if _SPACE_DEMO:
gr.HTML(
'
'
'💡'
'
'
'Demo interaktif di Hugging Face Space. '
'Hasil OCR, tutor, latihan, insight guru, dan suara di halaman ini '
'adalah contoh kurasi berbahasa Indonesia supaya bisa dicoba di CPU gratis. '
'Tutor Gemma 4 lengkap, termasuk Vision, tetap berjalan secara offline '
'di komputer kamu lewat Ollama. Panduan lokal ada di RUN.md pada repositori GitHub.'
'
Upload atau foto kode tulisan tangan Python — '
'Vision AI akan membacanya langsung tanpa library OCR eksternal. '
'Sempurna untuk mendigitalisasi catatan tulisan tangan.
'
)
# Demo button untuk OCR
with gr.Row():
btn_demo_ocr = gr.Button(f"📺 {DEMO_BUTTON_LABEL}", variant="secondary", size="sm", scale=1)
demo_ocr_status = gr.HTML(value="", scale=3)
# Visual guide untuk upload area
gr.HTML("""
💡
Tips untuk hasil terbaik:
✓ Pastikan pencahayaan cukup terang
✓ Tulisan terlihat jelas, tidak blur
✓ Foto dari atas dengan posisi lurus
""")
with gr.Row(equal_height=True):
with gr.Column(scale=1, elem_classes="cb-card-col"):
gr.HTML('
📸 1. Input Foto
Pilih atau ambil foto tulisan tangan
')
inp_img = gr.Image(
label="Foto Kode Tulisan Tangan",
show_label=False,
type="filepath",
sources=["upload", "webcam", "clipboard"],
height=320,
elem_classes="upload-area",
)
btn_ocr = gr.Button("✨ Ekstrak dengan Vision AI", variant="primary", size="lg")
out_ocr_info = gr.HTML()
with gr.Column(scale=1, elem_classes="cb-card-col"):
gr.HTML('
Tulis atau tempel kode Python di sebelah kiri — AI akan menjalankannya, menganalisa, '
'dan memberikan feedback yang actionable dalam bahasa pilihanmu. '
'Bukan jawaban langsung — tutor akan membimbing kamu untuk berpikir sendiri.
'
)
# Demo buttons untuk AI Tutor
with gr.Row():
btn_demo_tutor_error = gr.Button("📺 Demo: Code with Error", variant="secondary", size="sm", scale=1)
btn_demo_tutor_success = gr.Button("📺 Demo: Code Success", variant="secondary", size="sm", scale=1)
demo_tutor_status = gr.HTML(value="", scale=2)
# Tambah mascot intro
gr.HTML("""
🤖
Halo! Aku CodeBot, teman belajar coding-mu! 👋
Aku akan membantu kamu memahami kode dan memperbaiki error. Yuk mulai belajar!
""")
with gr.Row(equal_height=True):
with gr.Column(scale=1, elem_classes="cb-card-col"):
gr.HTML('
💻 1. Ruang Kode
Tulis atau tempel kode Python di sini
')
inp_code = gr.Code(
language="python", lines=13, label="Editor Kode", show_label=False,
value='nama = "Adik"\numur = 10\nprint("Halo " + nama + ", kamu berusia " + umur)',
)
with gr.Row():
inp_sid = gr.Textbox(value="1", label="ID Siswa", scale=1)
inp_level = gr.Dropdown(
["beginner", "intermediate", "advanced"],
value="beginner", label="Level", scale=2,
)
inp_ex_id = gr.Textbox(label="ID Latihan (opsional)", placeholder="contoh: hello_print")
btn_tutor = gr.Button("🚀 Analisa dengan AI Tutor", variant="primary", size="lg")
with gr.Column(scale=1, elem_classes="cb-card-col"):
gr.HTML('
🤖 2. Feedback CodeBot
Hasil analisis, error, dan perbaikan
')
out_status = gr.HTML()
with gr.Tabs():
with gr.Tab("💬 Feedback AI"):
out_fb = gr.Markdown()
with gr.Tab("⚙️ Output Eksekusi"):
out_exec = gr.Textbox(lines=9, label="Output Program", show_label=False)
with gr.Tab("✅ Kode Diperbaiki"):
out_fix = gr.Code(language="python", lines=11, show_label=False)
btn_tutor.click(
h_tutor,
[inp_code, inp_sid, inp_level, inp_ex_id, lang_global],
[out_exec, out_fb, out_fix, out_status],
)
# Load the curated sample, then analyse the values just written into the editor.
btn_demo_tutor_error.click(
demo_load_tutor_error,
[],
[inp_code, inp_sid, inp_level, inp_ex_id, demo_tutor_status],
).then(
h_tutor,
[inp_code, inp_sid, inp_level, inp_ex_id, lang_global],
[out_exec, out_fb, out_fix, out_status],
)
btn_demo_tutor_success.click(
demo_load_tutor_success,
[],
[inp_code, inp_sid, inp_level, inp_ex_id, demo_tutor_status],
).then(
h_tutor,
[inp_code, inp_sid, inp_level, inp_ex_id, lang_global],
[out_exec, out_fb, out_fix, out_status],
)
gr.HTML('')
gr.HTML(
'
💡'
'
Sistem Hint Bertahap — '
'AI tidak akan langsung memberikan jawaban. '
'Pilih level hint: 1 = pertanyaan pemandu, 2 = lokasi error, 3 = solusi lengkap.
'
)
with gr.Row(equal_height=True):
with gr.Column(scale=1, elem_classes="cb-card-col"):
gr.HTML('
❓ Masih Bingung?
Tanya detail error yang terjadi
')
inp_err = gr.Textbox(label="Pesan Error", placeholder="Tempel error dari output di atas...", show_label=False)
inp_hint_lvl = gr.Slider(1, 3, step=1, value=1, label="Level Bantuan (1=Ringan, 3=Penuh)")
btn_hint = gr.Button("💡 Minta Hint", variant="primary", size="lg")
with gr.Column(scale=1, elem_classes="cb-card-col"):
gr.HTML('
Untuk pengalaman belajar yang lebih mudah — '
'rekam pertanyaan dengan suara, dan CodeBot akan menjawab dengan suara alami. '
'Sepenuhnya dapat diproses secara offline.
'
)
# Tambah mascot intro untuk voice mode
gr.HTML("""
🎤
Ayo ngobrol dengan CodeBot! 🗣️
Tanya apa saja tentang coding, aku akan jawab dengan suara yang mudah dipahami.
""")
with gr.Row(equal_height=True):
with gr.Column(scale=1, elem_classes="cb-card-col"):
gr.HTML('
Monitor the entire class in one view. '
'AI analyzes learning patterns and provides '
'concrete, actionable teaching recommendations.
'
)
with gr.Tabs():
with gr.Tab("📊 Class Dashboard"):
btn_dash = gr.Button("🔄 Refresh Dashboard", variant="primary")
out_dash = gr.HTML()
btn_dash.click(h_dashboard, [], [out_dash])
with gr.Tab("🤖 AI Insight"):
if _SPACE_DEMO:
gr.HTML(
'
'
'💡'
'
Insight guru di demo ini tampil segera '
'sebagai teks kurasi Bahasa Indonesia dari data dashboard. '
'Tidak memanggil Gemma.
'
'
'
)
else:
gr.HTML(
'
'
'⏱️'
'
The AI may take 30–60 seconds '
'to analyze the class data and generate recommendations.