syncmaster3 / summarizer.py
aseelflihan's picture
move actual project files into root folder
1138072
# 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 أسئلة