Spaces:
Sleeping
Sleeping
Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172import osimport reimport numpy as npimport gradio as grfrom pypdf import PdfReaderfrom docx import Documentfrom sentence_transformers import SentenceTransformerfrom huggingface_hub import InferenceClient
# ---------- الإعدادات ----------MODEL_ID = os.environ.get("MODEL_ID", "Qwen/Qwen2.5-72B-Instruct")EMBED_ID = "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"CHUNK_WORDS = 220OVERLAP_WORDS = 40
embedder = SentenceTransformer(EMBED_ID)client = InferenceClient(model=MODEL_ID, token=os.environ.get("HF_TOKEN"))
SYSTEM_PROMPT = """You are a strict teaching assistant for ONE specific course.You will receive: (1) the course LEVEL description, (2) EXCERPTS from the coursematerial 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 = embedder.encode(chunks, normalize_embeddings=True) index = {"chunks": chunks, "sources": sources, "vecs": vecs} return index, f"✅ تمت قراءة {len(files)} ملف(ات) وتقسيمها إلى {len(chunks)} مقطع."
# ---------- البحث ----------def retrieve(index, query: str, k: int): q = embedder.encode([query], normalize_embeddings=True)[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_completion( 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()app.pyAdded+172