# يجب استيراد spaces قبل أي مكتبة أخرى (مطلوب لعتاد ZeroGPU) try: import spaces gpu = spaces.GPU except ImportError: # على CPU العادي def gpu(f): return f import os import re import numpy as np import gradio as gr from pypdf import PdfReader from docx import Document from sentence_transformers import SentenceTransformer from groq import Groq # ---------- الإعدادات ---------- MODEL_ID = os.environ.get("MODEL_ID", "llama-3.3-70b-versatile") EMBED_ID = "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2" CHUNK_WORDS = 220 OVERLAP_WORDS = 40 embedder = SentenceTransformer(EMBED_ID) client = Groq(api_key=os.environ.get("GROQ_API_KEY")) @gpu def encode(texts): return embedder.encode(texts, normalize_embeddings=True) SYSTEM_PROMPT = """You are a strict teaching assistant for ONE specific course. You will receive: (1) the course LEVEL description, (2) EXCERPTS from the course material uploaded by the teacher/student, and (3) an ASSIGNMENT. Rules (must follow): 1. Solve the assignment ONLY using methods, definitions, formulas, and notation that appear in the EXCERPTS, or basic prerequisites that clearly come before this course level. 2. NEVER use concepts, theorems, shortcuts, or techniques from a higher level or that were not covered in the excerpts. If a problem would normally be easier with an advanced tool, solve it using the course's own tools instead. 3. If a question (or part of it) cannot be solved with the provided material, do NOT solve it. Write: "Not covered in the uploaded material" and briefly say what topic is missing. 4. Show the solution step by step, in the same style as the course material. 5. After each solution, mention which file/excerpt the method came from, like [Source: filename]. 6. Answer in the same language as the assignment (Arabic if the assignment is Arabic). """ # ---------- قراءة الملفات ---------- def read_file(path: str) -> str: ext = os.path.splitext(path)[1].lower() if ext == ".pdf": reader = PdfReader(path) return "\n".join((p.extract_text() or "") for p in reader.pages) if ext == ".docx": doc = Document(path) return "\n".join(p.text for p in doc.paragraphs) if ext in (".txt", ".md"): with open(path, "r", encoding="utf-8", errors="ignore") as f: return f.read() return "" def chunk_text(text: str): words = text.split() step = CHUNK_WORDS - OVERLAP_WORDS for i in range(0, len(words), step): piece = " ".join(words[i:i + CHUNK_WORDS]) if len(piece.strip()) > 30: yield piece def get_path(f): return f if isinstance(f, str) else getattr(f, "name", None) # ---------- بناء الفهرس ---------- def build_index(files): if not files: return None, "⚠️ ارفع ملفات المادة أولاً." chunks, sources = [], [] for f in files: path = get_path(f) name = os.path.basename(path) text = read_file(path) for c in chunk_text(text): chunks.append(c) sources.append(name) if not chunks: return None, "⚠️ لم أستطع استخراج نص من الملفات (قد تكون صوراً ممسوحة ضوئياً)." vecs = encode(chunks) index = {"chunks": chunks, "sources": sources, "vecs": vecs} return index, f"✅ تمت قراءة {len(files)} ملف(ات) وتقسيمها إلى {len(chunks)} مقطع." # ---------- البحث ---------- def retrieve(index, query: str, k: int): q = encode([query])[0] scores = index["vecs"] @ q top = np.argsort(-scores)[:k] return [(int(i), float(scores[i])) for i in top] def split_questions(text: str): parts = re.split(r"\n\s*\n|\n(?=\s*(?:\d+[\).\-]|[أ-ي]\)|[a-zA-Z]\)|س\d*))", text) return [p.strip() for p in parts if p and len(p.strip()) > 8] # ---------- حل الواجب ---------- def solve(index, assignment_text, assignment_file, level): if index is None: return "⚠️ ابنِ الفهرس أولاً (ارفع الملفات واضغط الزر)." text = assignment_text or "" if assignment_file: text += "\n" + read_file(get_path(assignment_file)) text = text.strip() if not text: return "⚠️ اكتب الواجب أو ارفعه." # اجمع المقاطع الأقرب للواجب كله ولكل سؤال على حدة picked = {} for i, s in retrieve(index, text[:2000], 6): picked[i] = s for q in split_questions(text)[:15]: for i, s in retrieve(index, q, 3): picked[i] = max(s, picked.get(i, 0)) ordered = sorted(picked, key=lambda i: -picked[i])[:14] context = "\n\n".join( f"[Source: {index['sources'][i]}]\n{index['chunks'][i]}" for i in ordered ) user_msg = ( f"COURSE LEVEL:\n{level or 'Not specified - assume the level of the excerpts.'}\n\n" f"COURSE EXCERPTS:\n{context}\n\n" f"ASSIGNMENT:\n{text}" ) try: resp = client.chat.completions.create( model=MODEL_ID, messages=[ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": user_msg}, ], max_tokens=2500, temperature=0.2, ) return resp.choices[0].message.content except Exception as e: return f"❌ خطأ في استدعاء النموذج: {e}" # ---------- الواجهة ---------- with gr.Blocks(title="مساعد حل الواجبات حسب المادة") as demo: gr.Markdown("# 📚 مساعد حل الواجبات حسب مستوى المادة\n" "يحل **فقط** بما ورد في ملفاتك، وإن لم يجد في الملفات ما يكفي يخبرك.") index_state = gr.State(None) with gr.Row(): with gr.Column(): files = gr.File(label="ملفات المادة (PDF / DOCX / TXT)", file_count="multiple", file_types=[".pdf", ".docx", ".txt", ".md"]) level = gr.Textbox(label="وصف مستوى المادة", placeholder="مثال: تفاضل وتكامل 1 - السنة الأولى جامعة") build_btn = gr.Button("1) قراءة الملفات", variant="secondary") status = gr.Markdown() with gr.Column(): assignment = gr.Textbox(label="الواجب", lines=8, placeholder="الصق أسئلة الواجب هنا") assignment_file = gr.File(label="أو ارفع ملف الواجب (اختياري)", file_types=[".pdf", ".docx", ".txt"]) solve_btn = gr.Button("2) حل الواجب", variant="primary") answer = gr.Markdown(label="الحل") build_btn.click(build_index, files, [index_state, status]) solve_btn.click(solve, [index_state, assignment, assignment_file, level], answer) demo.launch()