File size: 9,063 Bytes
9830db9
 
 
 
 
 
 
 
 
 
 
 
 
13be81b
9830db9
 
 
 
 
 
 
13be81b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9830db9
 
13be81b
 
 
 
9830db9
13be81b
9830db9
 
13be81b
 
 
 
 
9830db9
13be81b
9830db9
 
 
 
13be81b
9830db9
 
 
13be81b
 
9830db9
 
 
 
 
 
13be81b
 
 
 
 
 
 
 
9830db9
 
13be81b
 
9830db9
 
 
 
 
 
 
 
13be81b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9830db9
 
 
 
 
 
 
 
13be81b
9830db9
 
 
 
 
 
 
 
 
74fb7d2
 
9830db9
 
 
74fb7d2
 
9830db9
13be81b
 
 
 
 
 
 
 
 
 
74fb7d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9830db9
 
 
13be81b
74fb7d2
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

import gradio as gr
from transformers import AutoTokenizer, AutoModel
import torch
import numpy as np

class ContractAnalyzer:
    def __init__(self):
        print("جاري تحميل النموذج...")
        self.tokenizer = AutoTokenizer.from_pretrained("aubmindlab/bert-large-arabertv2")
        self.model = AutoModel.from_pretrained("aubmindlab/bert-large-arabertv2")
        print("تم تحميل النموذج بنجاح!")

        # الكلمات المفتاحية القانونية
        self.legal_keywords = [
            "يلتزم", "يتعهد", "يحق", "لا يحق", "شرط جزائي",
            "فسخ العقد", "إنهاء", "تعويض", "غرامة", "مدة العقد",
            "طرف أول", "طرف ثاني", "قيمة العقد", "التزامات", "سداد",
            "دفعات", "ضمان", "مخالفة", "إخلال", "قوة قاهرة"
        ]

        # قالب التحليل (Prompt)
        self.analysis_prompt = """
        تحليل العقد القانوني:
        
        1. معلومات أساسية:
        - تاريخ العقد: {date}
        - الأطراف المتعاقدة: {parties}
        - موضوع العقد: {subject}
        
        2. تحليل البنود الرئيسية:
        {clauses_analysis}
        
        3. الالتزامات:
        أ. التزامات الطرف الأول:
        {party1_obligations}
        
        ب. التزامات الطرف الثاني:
        {party2_obligations}
        
        4. المخاطر المحتملة:
        {risks}
        
        5. العناصر المفقودة أو غير الواضحة:
        {missing_elements}
        
        6. توصيات قانونية:
        {recommendations}
        """

    def extract_contract_info(self, text):
        """استخراج المعلومات الأساسية من العقد"""
        info = {
            "date": "غير محدد",
            "parties": [],
            "subject": "غير محدد"
        }
        
        # البحث عن التاريخ
        date_indicators = ["بتاريخ", "في يوم", "الموافق"]
        for indicator in date_indicators:
            if indicator in text:
                # استخراج التاريخ باستخدام تعبير نمطي بسيط
                start_idx = text.find(indicator)
                end_idx = text.find("\n", start_idx)
                if end_idx == -1:
                    end_idx = text.find(".", start_idx)
                if end_idx != -1:
                    info["date"] = text[start_idx:end_idx].strip()
        
        # البحث عن الأطراف
        party_indicators = ["طرف أول", "طرف ثاني", "الطرف الأول", "الطرف الثاني"]
        for indicator in party_indicators:
            if indicator in text:
                start_idx = text.find(indicator)
                end_idx = text.find("\n", start_idx)
                if end_idx == -1:
                    end_idx = text.find(".", start_idx)
                if end_idx != -1:
                    info["parties"].append(text[start_idx:end_idx].strip())
        
        return info

    def analyze_contract(self, contract_text):
        try:
            # استخراج المعلومات الأساسية
            contract_info = self.extract_contract_info(contract_text)
            
            # تحليل البنود والمخاطر
            sentences = contract_text.split('.')
            
            results = {
                "important_clauses": [],
                "party1_obligations": [],
                "party2_obligations": [],
                "risks": [],
                "missing_elements": [],
                "recommendations": []
            }
            
            # تحليل كل جملة
            for sentence in sentences:
                if len(sentence.strip()) < 5:
                    continue
                
                # تحويل النص إلى تمثيل رقمي
                inputs = self.tokenizer(sentence, return_tensors="pt", padding=True, truncation=True)
                outputs = self.model(**inputs)
                
                # تحليل البنود المهمة
                for keyword in self.legal_keywords:
                    if keyword in sentence:
                        results["important_clauses"].append({
                            "text": sentence.strip(),
                            "keyword": keyword
                        })
                
                # تحليل الالتزامات
                if "طرف أول" in sentence or "الطرف الأول" in sentence:
                    results["party1_obligations"].append(sentence.strip())
                elif "طرف ثاني" in sentence or "الطرف الثاني" in sentence:
                    results["party2_obligations"].append(sentence.strip())
                
                # تحليل المخاطر
                risk_words = ["مخالفة", "خرق", "نزاع", "خلاف", "إخلال", "فسخ"]
                if any(word in sentence.lower() for word in risk_words):
                    results["risks"].append(sentence.strip())
            
            # التحقق من العناصر المفقودة
            required_elements = [
                "مدة العقد", "قيمة العقد", "التزامات الطرفين",
                "طريقة السداد", "الضمانات", "شروط الإنهاء"
            ]
            for element in required_elements:
                if not any(element in s for s in sentences):
                    results["missing_elements"].append(element)
                    results["recommendations"].append(f"يجب إضافة {element} بشكل واضح في العقد")
            
            # تنسيق النتائج باستخدام القالب
            formatted_results = self.analysis_prompt.format(
                date=contract_info["date"],
                parties="\n".join(contract_info["parties"]) or "غير محدد",
                subject=contract_info["subject"],
                clauses_analysis="\n".join([f"• {clause['keyword']}: {clause['text']}" for clause in results["important_clauses"]]),
                party1_obligations="\n".join([f"• {ob}" for ob in results["party1_obligations"]]) or "غير محدد",
                party2_obligations="\n".join([f"• {ob}" for ob in results["party2_obligations"]]) or "غير محدد",
                risks="\n".join([f"• {risk}" for risk in results["risks"]]) or "لا توجد مخاطر واضحة",
                missing_elements="\n".join([f"• {element}" for element in results["missing_elements"]]) or "لا توجد عناصر مفقودة",
                recommendations="\n".join([f"• {rec}" for rec in results["recommendations"]]) or "لا توجد توصيات إضافية"
            )
            
            return formatted_results

        except Exception as e:
            return f"حدث خطأ أثناء التحليل: {str(e)}"

# إنشاء كائن المحلل
analyzer = ContractAnalyzer()

# دالة التحليل لواجهة gradio
def analyze_text(text):
    return analyzer.analyze_contract(text)

# تكوين واجهة gradio
iface = gr.Interface(
    fn=analyze_text,
    inputs=gr.Textbox(
        placeholder="أدخل نص العقد هنا...",
        label="نص العقد",
        lines=30,
        rtl=True,  # إضافة دعم RTL للمدخلات
    ),
    outputs=gr.Textbox(
        label="نتائج التحليل",
        lines=20,
        rtl=True,  # إضافة دعم RTL للمخرجات
    ),
    title="محلل العقود القانونية المتقدم",
    description="""
    قم بإدخال نص العقد القانوني للحصول على تحليل شامل يتضمن:
    • المعلومات الأساسية للعقد
    • تحليل البنود الرئيسية
    • التزامات كل طرف
    • المخاطر المحتملة
    • العناصر المفقودة
    • التوصيات القانونية
    """,
    theme=gr.themes.Soft(
        primary_hue="blue",
        secondary_hue="blue",
        neutral_hue="blue",
        text_direction="rtl",  # تعيين اتجاه النص من اليمين إلى اليسار
    ),
    css="""
        .gradio-container {
            direction: rtl !important;
            text-align: right !important;
        }
        .output-markdown {
            direction: rtl !important;
            text-align: right !important;
        }
        .input-markdown {
            direction: rtl !important;
            text-align: right !important;
        }
        label {
            text-align: right !important;
        }
        .prose {
            direction: rtl !important;
            text-align: right !important;
        }
    """
)

# تشغيل الواجهة
iface.launch(share=True, debug=True)