Spaces:
Running
Running
| """ | |
| محمّل ملفات JSON لقاعدة المعرفة | |
| JSON Knowledge Base Loader for HR Genie | |
| """ | |
| import os | |
| import json | |
| from typing import List, Dict, Any, Optional | |
| from utils.rag_chain import Document | |
| class JSONKnowledgeLoader: | |
| """محمّل ملفات JSON لقاعدة المعرفة""" | |
| def __init__(self, data_path: str = "data"): | |
| """ | |
| تهيئة المحمّل | |
| Args: | |
| data_path: مسار مجلد البيانات | |
| """ | |
| self.data_path = data_path | |
| self.validated_path = os.path.join(data_path, "validated") | |
| self.processed_path = os.path.join(data_path, "processed") | |
| self.raw_path = os.path.join(data_path, "raw") | |
| def load_json_file(self, filepath: str) -> Any: | |
| """تحميل ملف JSON واحد""" | |
| try: | |
| with open(filepath, 'r', encoding='utf-8') as f: | |
| return json.load(f) | |
| except Exception as e: | |
| print(f"❌ خطأ في تحميل الملف {filepath}: {e}") | |
| return None | |
| def load_policy_qa(self) -> List[Dict]: | |
| """تحميل بيانات السياسات والأسئلة الشائعة""" | |
| filepath = os.path.join(self.validated_path, "policy_qa_validated.json") | |
| data = self.load_json_file(filepath) | |
| return data if data else [] | |
| def load_hr_conversations(self) -> List[Dict]: | |
| """تحميل المحادثات HR""" | |
| filepath = os.path.join(self.validated_path, "hr_conversations.json") | |
| data = self.load_json_file(filepath) | |
| return data if data else [] | |
| def load_training_data(self) -> List[Dict]: | |
| """تحميل بيانات التدريب المنسقة""" | |
| filepath = os.path.join(self.processed_path, "hr_training_formatted.json") | |
| data = self.load_json_file(filepath) | |
| return data if data else [] | |
| def load_all_data(self) -> Dict[str, List]: | |
| """تحميل جميع البيانات المتاحة""" | |
| return { | |
| "policy_qa": self.load_policy_qa(), | |
| "hr_conversations": self.load_hr_conversations(), | |
| "training_data": self.load_training_data() | |
| } | |
| def convert_to_documents(self) -> List[Document]: | |
| """ | |
| تحويل البيانات إلى LangChain Documents للـ RAG | |
| Returns: | |
| قائمة من المستندات | |
| """ | |
| documents = [] | |
| # تحميل بيانات السياسات | |
| policy_qa = self.load_policy_qa() | |
| for idx, item in enumerate(policy_qa): | |
| question = item.get('question', '') | |
| answer = item.get('answer', '') | |
| category = item.get('category', 'عام') | |
| if question and answer: | |
| # إنشاء محتوى المستند | |
| content = f"السؤال: {question}\nالإجابة: {answer}" | |
| doc = Document( | |
| page_content=content, | |
| metadata={ | |
| "source": "policy_qa", | |
| "question": question, | |
| "answer": answer, | |
| "category": category or "عام", | |
| "doc_id": f"policy_{idx}", | |
| "type": "qa" | |
| } | |
| ) | |
| documents.append(doc) | |
| # تحميل المحادثات | |
| conversations = self.load_hr_conversations() | |
| for idx, item in enumerate(conversations): | |
| question = item.get('question', '') | |
| answer = item.get('answer', '') | |
| if question and answer: | |
| content = f"السؤال: {question}\nالإجابة: {answer}" | |
| doc = Document( | |
| page_content=content, | |
| metadata={ | |
| "source": "hr_conversations", | |
| "question": question, | |
| "answer": answer, | |
| "doc_id": f"conv_{idx}", | |
| "type": "conversation" | |
| } | |
| ) | |
| documents.append(doc) | |
| print(f"✅ تم تحميل {len(documents)} مستند") | |
| return documents | |
| def search_by_keywords(self, keywords: List[str], data: Optional[List[Dict]] = None) -> List[Dict]: | |
| """ | |
| البحث في البيانات بالكلمات المفتاحية | |
| Args: | |
| keywords: قائمة الكلمات المفتاحية | |
| data: البيانات للبحث فيها (اختياري) | |
| Returns: | |
| قائمة النتائج المطابقة | |
| """ | |
| if data is None: | |
| data = self.load_policy_qa() + self.load_hr_conversations() | |
| results = [] | |
| for item in data: | |
| text = f"{item.get('question', '')} {item.get('answer', '')}".lower() | |
| if any(keyword.lower() in text for keyword in keywords): | |
| results.append(item) | |
| return results | |
| def get_stats(self) -> Dict: | |
| """الحصول على إحصائيات قاعدة المعرفة""" | |
| policy_qa = self.load_policy_qa() | |
| conversations = self.load_hr_conversations() | |
| training_data = self.load_training_data() | |
| # تحليل الفئات | |
| categories = {} | |
| for item in policy_qa: | |
| cat = item.get('category', 'عام') or 'عام' | |
| categories[cat] = categories.get(cat, 0) + 1 | |
| return { | |
| "total_policy_qa": len(policy_qa), | |
| "total_conversations": len(conversations), | |
| "total_training_samples": len(training_data), | |
| "total_documents": len(policy_qa) + len(conversations), | |
| "categories": categories, | |
| "data_sources": ["policy_qa_validated.json", "hr_conversations.json", "hr_training_formatted.json"] | |
| } | |
| def get_unique_questions(self) -> List[str]: | |
| """الحصول على قائمة الأسئلة الفريدة""" | |
| all_data = self.load_policy_qa() + self.load_hr_conversations() | |
| questions = set() | |
| for item in all_data: | |
| q = item.get('question', '').strip() | |
| if q: | |
| questions.add(q) | |
| return list(questions) | |
| if __name__ == "__main__": | |
| # اختبار المحمّل | |
| loader = JSONKnowledgeLoader() | |
| stats = loader.get_stats() | |
| print("📊 إحصائيات قاعدة المعرفة:") | |
| for key, value in stats.items(): | |
| print(f" {key}: {value}") | |