Spaces:
Sleeping

File size: 7,133 Bytes
c63bedf
 
 
 
 
 
 
 
7361d07
 
 
 
 
 
 
eb2b3ba
7361d07
 
eb2b3ba
7361d07
 
 
 
 
eb2b3ba
7361d07
c63bedf
 
 
 
 
7361d07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c63bedf
7361d07
 
 
 
 
 
c63bedf
7361d07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb2b3ba
 
7361d07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# يجب استيراد 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()