File size: 10,618 Bytes
6609c06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
# summarizer.py - نظام الملخص الذكي للمحاضرات

from translator import get_translator
from typing import Tuple, List, Dict, Optional
import re

class LectureSummarizer:
    """نظام الملخص الذكي للمحاضرات الدراسية"""
    
    def __init__(self):
        self.translator = get_translator()
    
    def generate_summary(self, text: str, language: str = 'ar') -> Tuple[Optional[str], Optional[str]]:
        """
        إنشاء ملخص ذكي للنص
        
        Args:
            text: النص المراد تلخيصه
            language: لغة الملخص ('ar' للعربية، 'en' للإنجليزية)
        
        Returns:
            Tuple of (summary, error_message)
        """
        if not self.translator or not self.translator.model:
            return None, "خدمة الذكاء الاصطناعي غير متوفرة"
        
        if not text or len(text.strip()) < 50:
            return None, "النص قصير جداً لإنشاء ملخص مفيد"
        
        try:
            prompt = self._create_summary_prompt(text, language)
            
            response = self.translator.model.generate_content(prompt)
            
            if response and hasattr(response, 'text') and response.text:
                summary = response.text.strip()
                summary = self._clean_summary_output(summary)
                return summary, None
            else:
                return None, "فشل في إنشاء الملخص"
                
        except Exception as e:
            return None, f"خطأ في إنشاء الملخص: {str(e)}"
    
    def extract_key_points(self, text: str, language: str = 'ar') -> Tuple[Optional[List[str]], Optional[str]]:
        """
        استخراج النقاط الرئيسية من النص
        
        Args:
            text: النص المراد استخراج النقاط منه
            language: لغة النقاط
        
        Returns:
            Tuple of (key_points_list, error_message)
        """
        if not self.translator or not self.translator.model:
            return None, "خدمة الذكاء الاصطناعي غير متوفرة"
        
        try:
            prompt = self._create_key_points_prompt(text, language)
            
            response = self.translator.model.generate_content(prompt)

            if response and hasattr(response, 'text') and response.text:
                key_points_text = response.text.strip()
                key_points = self._parse_key_points(key_points_text)
                return key_points, None
            else:
                return None, "فشل في استخراج النقاط الرئيسية"
                
        except Exception as e:
            return None, f"خطأ في استخراج النقاط: {str(e)}"
    
    def generate_study_notes(self, text: str, subject: str = "", language: str = 'ar') -> Tuple[Optional[Dict], Optional[str]]:
        """
        إنشاء مذكرة دراسية شاملة
        
        Args:
            text: النص الأصلي
            subject: المادة الدراسية
            language: لغة المذكرة
        
        Returns:
            Tuple of (study_notes_dict, error_message)
        """
        try:
            # إنشاء الملخص
            summary, summary_error = self.generate_summary(text, language)
            if summary_error and not summary:
                return None, summary_error
            
            # استخراج النقاط الرئيسية
            key_points, points_error = self.extract_key_points(text, language)
            if points_error and not key_points:
                key_points = []
            
            # إنشاء أسئلة مراجعة
            review_questions, questions_error = self.generate_review_questions(text, language)
            if questions_error and not review_questions:
                review_questions = []
            
            study_notes = {
                'summary': summary or "لم يتم إنشاء ملخص",
                'key_points': key_points or [],
                'review_questions': review_questions or [],
                'subject': subject,
                'word_count': len(text.split()),
                'estimated_reading_time': max(1, len(text.split()) // 200)  # دقائق تقريبية
            }
            
            return study_notes, None
            
        except Exception as e:
            return None, f"خطأ في إنشاء المذكرة: {str(e)}"
    
    def generate_review_questions(self, text: str, language: str = 'ar') -> Tuple[Optional[List[str]], Optional[str]]:
        """
        إنشاء أسئلة مراجعة من النص
        
        Args:
            text: النص المراد إنشاء أسئلة منه
            language: لغة الأسئلة
        
        Returns:
            Tuple of (questions_list, error_message)
        """
        if not self.translator or not self.translator.model:
            return None, "خدمة الذكاء الاصطناعي غير متوفرة"
        
        try:
            prompt = self._create_questions_prompt(text, language)
            
            response = self.translator.model.generate_content(prompt)
            
            if response and hasattr(response, 'text') and response.text:
                questions_text = response.text.strip()
                questions = self._parse_questions(questions_text)
                return questions, None
            else:
                return None, "فشل في إنشاء أسئلة المراجعة"
                
        except Exception as e:
            return None, f"خطأ في إنشاء الأسئلة: {str(e)}"
    
    def _create_summary_prompt(self, text: str, language: str) -> str:
        """إنشاء prompt للملخص"""
        if language == 'ar':
            return f"""
قم بإنشاء ملخص شامل ومفيد لهذا النص من محاضرة دراسية:

متطلبات الملخص:
1. اكتب بالعربية الفصحى الواضحة
2. اذكر الموضوع الرئيسي والأفكار المهمة
3. رتب المعلومات بشكل منطقي
4. اجعل الملخص مناسب للطلاب الجامعيين
5. لا تتجاوز 200 كلمة
6. أضف العناوين الفرعية إذا لزم الأمر

النص:
{text}

الملخص:
"""
        else:
            return f"""
Create a comprehensive and useful summary of this lecture text:

Requirements:
1. Write in clear, academic English
2. Mention the main topic and important ideas  
3. Organize information logically
4. Make it suitable for university students
5. Don't exceed 200 words
6. Add subheadings if necessary

Text:
{text}

Summary:
"""
    
    def _create_key_points_prompt(self, text: str, language: str) -> str:
        """إنشاء prompt للنقاط الرئيسية"""
        if language == 'ar':
            return f"""
استخرج أهم النقاط الرئيسية من هذا النص:

متطلبات:
1. اكتب كل نقطة في سطر منفصل
2. ابدأ كل نقطة بـ "•" 
3. اجعل كل نقطة واضحة ومفيدة للدراسة
4. لا تزيد عن 8 نقاط
5. رتب النقاط حسب الأهمية

النص:
{text}

النقاط الرئيسية:
"""
        else:
            return f"""
Extract the most important key points from this text:

Requirements:
1. Write each point on a separate line
2. Start each point with "•"
3. Make each point clear and useful for studying
4. No more than 8 points
5. Order points by importance

Text:
{text}

Key Points:
"""
    
    def _create_questions_prompt(self, text: str, language: str) -> str:
        """إنشاء prompt لأسئلة المراجعة"""
        if language == 'ar':
            return f"""
أنشئ أسئلة مراجعة مفيدة من هذا النص:

متطلبات:
1. اكتب كل سؤال في سطر منفصل
2. ابدأ كل سؤال برقم (1، 2، 3...)
3. اجعل الأسئلة تغطي المفاهيم المهمة
4. تنوع في أنواع الأسئلة (ما، كيف، لماذا، اشرح)
5. لا تزيد عن 6 أسئلة
6. اجعل الأسئلة مناسبة للامتحانات

النص:
{text}

أسئلة المراجعة:
"""
        else:
            return f"""
Create useful review questions from this text:

Requirements:
1. Write each question on a separate line
2. Start each question with a number (1, 2, 3...)
3. Make questions cover important concepts
4. Vary question types (what, how, why, explain)
5. No more than 6 questions
6. Make questions suitable for exams

Text:
{text}

Review Questions:
"""
    
    def _clean_summary_output(self, text: str) -> str:
        """تنظيف نص الملخص"""
        # إزالة الرموز غير المرغوبة
        text = re.sub(r'\*+', '', text)
        text = re.sub(r'#+', '', text)
        text = text.strip()
        
        # تنظيف الأسطر الفارغة الزائدة
        text = re.sub(r'\n\s*\n', '\n\n', text)
        
        return text
    
    def _parse_key_points(self, text: str) -> List[str]:
        """تحليل النقاط الرئيسية من النص"""
        points = []
        lines = text.split('\n')
        
        for line in lines:
            line = line.strip()
            if line and (line.startswith('•') or line.startswith('-') or line.startswith('*')):
                # إزالة الرمز من البداية
                point = re.sub(r'^[•\-\*]\s*', '', line)
                if point:
                    points.append(point)
            elif line and re.match(r'^\d+\.', line):
                # نقاط مرقمة
                point = re.sub(r'^\d+\.\s*', '', line)
                if point:
                    points.append(point)
        
        return points[:8]  # حد أقصى 8 نقاط
    
    def _parse_questions(self, text: str) -> List[str]:
        """تحليل الأسئلة من النص"""
        questions = []
        lines = text.split('\n')
        
        for line in lines:
            line = line.strip()
            if line and ('؟' in line or '?' in line):
                # إزالة الترقيم من البداية
                question = re.sub(r'^\d+[\.\-\)]\s*', '', line)
                if question:
                    questions.append(question)
        
        return questions[:6]  # حد أقصى 6 أسئلة