Spaces:
Runtime error

File size: 32,113 Bytes
40cefb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
from fastapi import FastAPI, File, UploadFile, HTTPException, Depends, BackgroundTasks
from sqlalchemy.orm import Session
from sqlalchemy import func, desc, and_
from datetime import datetime, timedelta
import whisper
import openpyxl
import PyPDF2
import numpy as np
from transformers import pipeline, AutoTokenizer, AutoModelForSequenceClassification
from fastapi_jwt_auth import AuthJWT
from fastapi_jwt_auth.exceptions import AuthJWTException
import os
import json
import logging
from typing import Optional, List, Dict, Any
from contextlib import contextmanager
import asyncio

from database import *
from config import config
from utils import *

app = FastAPI(
    title="MyAIProject_v2",
    version="2.1",
    description="نظام تحليلي متقدم للبيانات المختلفة مع التعلم التراكمي",
    debug=False,
    docs_url="/docs",
    redoc_url="/redoc"
)

# إعداد التسجيل
logger = setup_logging()

# إعداد JWT
@AuthJWT.load_config
def get_config():
    return {
        "authjwt_secret_key": config.SECRET_KEY,
        "authjwt_algorithm": config.ALGORITHM,
        "authjwt_access_token_expires": timedelta(minutes=config.ACCESS_TOKEN_EXPIRE_MINUTES)
    }

# إنشاء جلسة قاعدة البيانات
def get_db():
    """إنشاء جلسة قاعدة البيانات"""
    db = get_db_session()
    try:
        yield db
    finally:
        db.close()

# إنشاء نموذج التصنيف المتعدد اللغات
def create_multilingual_classifier():
    """إنشاء نموذج التصنيف المتعدد اللغات"""
    try:
        # استخدام نموذج متعدد اللغات
        tokenizer = AutoTokenizer.from_pretrained("xlm-roberta-base")
        model = AutoModelForSequenceClassification.from_pretrained("xlm-roberta-base", num_labels=3)
        return pipeline("text-classification", model=model, tokenizer=tokenizer)
    except Exception as e:
        logger.error(f"Error creating multilingual classifier: {str(e)}")
        # استخدام نموذج احتياطي إذا فشل
        try:
            return pipeline("text-classification", model="cardiffnlp/twitter-roberta-base-sentiment-latest")
        except Exception as e2:
            logger.error(f"Error creating fallback classifier: {str(e2)}")
            return None

# إنشاء النموذج
try:
    classifier = create_multilingual_classifier()
    logger.info("Multilingual classifier loaded successfully")
except Exception as e:
    logger.error(f"Error loading classifier: {str(e)}")
    classifier = None

# تسجيل دخول المستخدم
@app.post("/login")
def login(username: str, password: str, Authorize: AuthJWT = Depends()):
    """تسجيل دخول المستخدم"""
    try:
        db = next(get_db())
        user = db.query(User).filter(User.username == username).first()
        
        if user and user.is_active and verify_password(password, user.password_hash):
            # التحقق من صلاحية المستخدم
            if user.role not in ['admin', 'analyst', 'viewer']:
                raise HTTPException(status_code=401, detail="دور المستخدم غير مسموح به")
            
            # تحديث آخر تسجيل دخول
            user.last_login = datetime.utcnow()
            db.commit()
            
            access_token = Authorize.create_access_token(
                subject=user.username,
                expires_time=timedelta(minutes=config.ACCESS_TOKEN_EXPIRE_MINUTES)
            )
            return {
                "access_token": access_token,
                "role": user.role,
                "user_id": user.id,
                "username": user.username,
                "first_name": user.first_name,
                "last_name": user.last_name
            }
        raise HTTPException(status_code=401, detail="اسم المستخدم أو كلمة المرور غير صحيحة")
    except Exception as e:
        logger.error(f"Login error: {str(e)}")
        raise HTTPException(status_code=401, detail="خطأ في تسجيل الدخول")

# تسجيل مستخدم جديد
@app.post("/register")
def register(
    username: str, 
    password: str, 
    email: str = None, 
    role: str = "viewer",
    first_name: str = None,
    last_name: str = None,
    db: Session = Depends(get_db)
):
    """تسجيل مستخدم جديد"""
    try:
        # التحقق من أن الدور صحيح
        if role not in ['admin', 'analyst', 'viewer']:
            raise HTTPException(status_code=400, detail="دور غير مسموح به")
        
        # التحقق من أن اسم المستخدم غير مستخدم
        existing_user = db.query(User).filter(User.username == username).first()
        if existing_user:
            raise HTTPException(status_code=400, detail="اسم المستخدم مستخدم بالفعل")
        
        # التحقق من البريد الإلكتروني
        if email:
            existing_email = db.query(User).filter(User.email == email).first()
            if existing_email:
                raise HTTPException(status_code=400, detail="البريد الإلكتروني مستخدم بالفعل")
        
        # تشفير كلمة المرور
        hashed_password = hash_password(password)
        
        # إنشاء المستخدم
        new_user = User(
            username=username,
            password_hash=hashed_password,
            email=email,
            role=role,
            first_name=first_name,
            last_name=last_name
        )
        
        db.add(new_user)
        db.commit()
        db.refresh(new_user)
        
        logger.info(f"New user registered: {username}")
        return {
            "message": "تم التسجيل بنجاح",
            "user_id": new_user.id,
            "username": new_user.username,
            "role": new_user.role
        }
    except Exception as e:
        logger.error(f"Registration error: {str(e)}")
        db.rollback()
        raise HTTPException(status_code=500, detail="خطأ في التسجيل")

# حفظ المحادثة
@app.post("/save_conversation")
def save_conversation(
    input_type: str, 
    input_content: str, 
    output_content: str, 
    risk_level: str = None, 
    confidence_score: float = None,
    metadata_info: str = None,
    Authorize: AuthJWT = Depends(),
    db: Session = Depends(get_db)
):
    """حفظ المحادثة"""
    try:
        Authorize.jwt_required()
        current_user = Authorize.get_jwt_subject()
        
        user = db.query(User).filter(User.username == current_user).first()
        if not user:
            raise HTTPException(status_code=401, detail="مستخدم غير مصرح به")
        
        # التحقق من نوع المدخل
        allowed_types = ['text', 'image', 'audio', 'video']
        if input_type not in allowed_types:
            raise HTTPException(status_code=400, detail="نوع المدخل غير مسموح به")
        
        # التحقق من مخاطر مقبولة
        if risk_level and risk_level not in ['Low', 'Medium', 'High']:
            raise HTTPException(status_code=400, detail="مستوى المخاطر غير مسموح به")
        
        # التحقق من حجم المحتوى
        if len(input_content) > 100000 or len(output_content) > 100000:
            raise HTTPException(status_code=400, detail="حجم المحتوى كبير جداً")
        
        # إنشاء المحادثة
        conversation = Conversation(
            user_id=user.id,
            input_type=input_type,
            input_content=input_content[:10000],  # تقييد الطول
            output_content=output_content[:10000],  # تقييد الطول
            risk_level=risk_level,
            confidence_score=confidence_score,
            metadata_info=metadata_info
        )
        
        db.add(conversation)
        db.commit()
        db.refresh(conversation)
        
        logger.info(f"Conversation saved for user {current_user}")
        return {
            "message": "تم حفظ المحادثة",
            "conversation_id": conversation.id,
            "timestamp": conversation.timestamp.isoformat()
        }
    except Exception as e:
        logger.error(f"Save conversation error: {str(e)}")
        db.rollback()
        raise HTTPException(status_code=500, detail="خطأ في حفظ المحادثة")

# تحليل النصوص (تحليل المخاطر)
def analyze_text_risk(text: str) -> tuple:
    """تحليل مخاطر النصوص باستخدام نموذج متعدد اللغات"""
    if not classifier:
        logger.warning("No classifier available, returning default risk")
        return "Medium Risk", 0.6
    
    try:
        # تحليل النص
        results = classifier(text, truncation=True, max_length=512)
        
        # تحليل النتائج
        labels = [r['label'] for r in results]
        scores = [r['score'] for r in results]
        
        # تحديد أعلى تقييم
        max_score = max(scores)
        best_label = labels[scores.index(max_score)]
        
        # تحويل التصنيف إلى مخاطر
        if any(keyword in best_label.upper() for keyword in ['NEGATIVE', 'HATE', 'ANGRY', 'ATTACK', 'THREAT']):
            risk_level = "High Risk"
        elif any(keyword in best_label.upper() for keyword in ['NEUTRAL', 'NEUTRALITY']):
            risk_level = "Medium Risk"
        else:
            risk_level = "Low Risk"
            
        return risk_level, max_score
        
    except Exception as e:
        logger.error(f"Error in text analysis: {str(e)}")
        return "Medium Risk", 0.6

# رفع ملف PDF
@app.post("/upload_pdf")
async def upload_pdf(
    file: UploadFile = File(...),
    Authorize: AuthJWT = Depends(),
    db: Session = Depends(get_db)
):
    """رفع ملف PDF"""
    try:
        Authorize.jwt_required()
        current_user = Authorize.get_jwt_subject()
        
        user = db.query(User).filter(User.username == current_user).first()
        if not user:
            raise HTTPException(status_code=401, detail="مستخدم غير مصرح به")
        
        # التحقق من نوع الملف
        if not validate_file_extension(file.filename):
            raise HTTPException(status_code=400, detail="نوع الملف غير مسموح به")
        
        # التحقق من حجم الملف
        if file.size > config.MAX_FILE_SIZE:
            raise HTTPException(status_code=400, detail="حجم الملف أكبر من الحد المسموح به")
        
        # حفظ الملف مؤقتاً
        temp_file_path = f"temp_{sanitize_filename(file.filename)}"
        with open(temp_file_path, "wb") as buffer:
            content = await file.read()
            buffer.write(content)
        
        # قراءة PDF
        try:
            with open(temp_file_path, "rb") as pdf_file:
                pdf_reader = PyPDF2.PdfReader(pdf_file)
                text = ""
                for page in pdf_reader.pages:
                    text += page.extract_text()
        except Exception as e:
            raise HTTPException(status_code=500, detail=f"خطأ في قراءة PDF: {str(e)}")
        finally:
            # حذف الملف المؤقت
            if os.path.exists(temp_file_path):
                os.remove(temp_file_path)
        
        # تحليل النص
        risk_level, confidence = analyze_text_risk(text)
        
        # حفظ المحادثة
        conversation = Conversation(
            user_id=user.id,
            input_type="pdf",
            input_content=f"ملف: {file.filename}",
            output_content=text[:500] + "...",
            risk_level=risk_level,
            confidence_score=confidence
        )
        
        db.add(conversation)
        db.commit()
        db.refresh(conversation)
        
        logger.info(f"PDF uploaded and analyzed for user {current_user}")
        return {
            "message": "تم رفع وتحليل PDF",
            "filename": file.filename,
            "risk_level": risk_level,
            "confidence": confidence,
            "character_count": len(text),
            "conversation_id": conversation.id
        }
    except Exception as e:
        logger.error(f"PDF upload error: {str(e)}")
        raise HTTPException(status_code=500, detail="خطأ في رفع ملف PDF")

# رفع ملف Excel
@app.post("/upload_excel")
async def upload_excel(
    file: UploadFile = File(...),
    Authorize: AuthJWT = Depends(),
    db: Session = Depends(get_db)
):
    """رفع ملف Excel"""
    try:
        Authorize.jwt_required()
        current_user = Authorize.get_jwt_subject()
        
        user = db.query(User).filter(User.username == current_user).first()
        if not user:
            raise HTTPException(status_code=401, detail="مستخدم غير مصرح به")
        
        # التحقق من نوع الملف
        if not validate_file_extension(file.filename):
            raise HTTPException(status_code=400, detail="نوع الملف غير مسموح به")
        
        # التحقق من حجم الملف
        if file.size > config.MAX_FILE_SIZE:
            raise HTTPException(status_code=400, detail="حجم الملف أكبر من الحد المسموح به")
        
        # حفظ الملف مؤقتاً
        temp_file_path = f"temp_{sanitize_filename(file.filename)}"
        with open(temp_file_path, "wb") as buffer:
            content = await file.read()
            buffer.write(content)
        
        # قراءة Excel
        try:
            workbook = openpyxl.load_workbook(temp_file_path)
            sheet = workbook.active
            data_rows = []
            for row in sheet.iter_rows(values_only=True):
                data_rows.append(str(row))
            
            text = "\n".join(data_rows[:10])  # فقط أول 10 صفوف
        except Exception as e:
            raise HTTPException(status_code=500, detail=f"خطأ في قراءة Excel: {str(e)}")
        finally:
            # حذف الملف المؤقت
            if os.path.exists(temp_file_path):
                os.remove(temp_file_path)
        
        # تحليل النص
        risk_level, confidence = analyze_text_risk(text)
        
        # حفظ المحادثة
        conversation = Conversation(
            user_id=user.id,
            input_type="excel",
            input_content=f"ملف: {file.filename}",
            output_content=text[:500] + "...",
            risk_level=risk_level,
            confidence_score=confidence
        )
        
        db.add(conversation)
        db.commit()
        db.refresh(conversation)
        
        logger.info(f"Excel uploaded and analyzed for user {current_user}")
        return {
            "message": "تم رفع وتحليل Excel",
            "filename": file.filename,
            "risk_level": risk_level,
            "confidence": confidence,
            "row_count": len(data_rows),
            "conversation_id": conversation.id
        }
    except Exception as e:
        logger.error(f"Excel upload error: {str(e)}")
        raise HTTPException(status_code=500, detail="خطأ في رفع ملف Excel")

# رفع ملف صوت
@app.post("/upload_audio")
async def upload_audio(
    file: UploadFile = File(...),
    Authorize: AuthJWT = Depends(),
    db: Session = Depends(get_db)
):
    """رفع ملف صوت"""
    try:
        Authorize.jwt_required()
        current_user = Authorize.get_jwt_subject()
        
        user = db.query(User).filter(User.username == current_user).first()
        if not user:
            raise HTTPException(status_code=401, detail="مستخدم غير مصرح به")
        
        # التحقق من نوع الملف
        if not validate_file_extension(file.filename):
            raise HTTPException(status_code=400, detail="نوع الملف غير مسموح به")
        
        # التحقق من حجم الملف
        if file.size > config.MAX_FILE_SIZE:
            raise HTTPException(status_code=400, detail="حجم الملف أكبر من الحد المسموح به")
        
        # حفظ الملف مؤقتاً
        temp_file_path = f"temp_{sanitize_filename(file.filename)}"
        with open(temp_file_path, "wb") as buffer:
            content = await file.read()
            buffer.write(content)
        
        # تحليل الصوت
        try:
            model = whisper.load_model("base")
            result = model.transcribe(temp_file_path)
            text = result["text"]
        except Exception as e:
            raise HTTPException(status_code=500, detail=f"خطأ في تحليل الصوت: {str(e)}")
        finally:
            # حذف الملف المؤقت
            if os.path.exists(temp_file_path):
                os.remove(temp_file_path)
        
        # تحليل النص
        risk_level, confidence = analyze_text_risk(text)
        
        # حفظ المحادثة
        conversation = Conversation(
            user_id=user.id,
            input_type="audio",
            input_content=f"ملف صوت: {file.filename}",
            output_content=text[:500] + "...",
            risk_level=risk_level,
            confidence_score=confidence
        )
        
        db.add(conversation)
        db.commit()
        db.refresh(conversation)
        
        logger.info(f"Audio uploaded and analyzed for user {current_user}")
        return {
            "message": "تم رفع وتحليل الصوت",
            "filename": file.filename,
            "risk_level": risk_level,
            "confidence": confidence,
            "transcribed_text": text[:200] + "...",
            "conversation_id": conversation.id
        }
    except Exception as e:
        logger.error(f"Audio upload error: {str(e)}")
        raise HTTPException(status_code=500, detail="خطأ في رفع ملف صوت")

# إضافة تقييم للمحادثة
@app.post("/add_feedback")
def add_feedback(
    conversation_id: int,
    actual_result: str,
    user_feedback: str,
    rating: int = None,
    Authorize: AuthJWT = Depends(),
    db: Session = Depends(get_db)
):
    """إضافة تقييم للمحادثة"""
    try:
        Authorize.jwt_required()
        current_user = Authorize.get_jwt_subject()
        
        user = db.query(User).filter(User.username == current_user).first()
        if not user:
            raise HTTPException(status_code=401, detail="مستخدم غير مصرح به")
        
        # التحقق من أن المستخدم مالك المحادثة
        conversation = db.query(Conversation).filter(
            Conversation.id == conversation_id,
            Conversation.user_id == user.id
        ).first()
        
        if not conversation:
            raise HTTPException(status_code=404, detail="المحادثة غير موجودة أو ليست لك")
        
        # التحقق من النتيجة الحقيقية
        if actual_result not in ['Low Risk', 'Medium Risk', 'High Risk']:
            raise HTTPException(status_code=400, detail="النتيجة الحقيقية غير مسموح بها")
        
        # التحقق من التقييم
        if rating is not None and (rating < 1 or rating > 5):
            raise HTTPException(status_code=400, detail="التقييم يجب أن يكون بين 1 و 5")
        
        # إنشاء التقييم
        feedback = Feedback(
            conversation_id=conversation_id,
            user_id=user.id,
            actual_result=actual_result,
            user_feedback=user_feedback,
            rating=rating
        )
        
        db.add(feedback)
        db.commit()
        db.refresh(feedback)
        
        logger.info(f"Feedback added for conversation {conversation_id} by user {current_user}")
        return {
            "message": "تم إضافة التقييم",
            "feedback_id": feedback.id
        }
    except Exception as e:
        logger.error(f"Add feedback error: {str(e)}")
        db.rollback()
        raise HTTPException(status_code=500, detail="خطأ في إضافة التقييم")

# الحصول على إحصائيات النظام
@app.get("/system_stats")
def get_system_stats(db: Session = Depends(get_db)):
    """الحصول على إحصائيات النظام"""
    try:
        total_users = db.query(func.count(User.id)).scalar()
        total_conversations = db.query(func.count(Conversation.id)).scalar()
        total_files = db.query(func.count(FileUpload.id)).scalar()
        total_tasks = db.query(func.count(Task.id)).scalar()
        
        # إحصائيات المخاطر
        risk_stats = db.query(
            Conversation.risk_level,
            func.count(Conversation.risk_level).label("count")
        ).group_by(Conversation.risk_level).all()
        
        risk_distribution = {stat.risk_level: stat.count for stat in risk_stats}
        
        # إحصائيات المستخدمين
        role_stats = db.query(
            User.role,
            func.count(User.role).label("count")
        ).group_by(User.role).all()
        
        role_distribution = {stat.role: stat.count for stat in role_stats}
        
        # إحصائيات الأحدث
        recent_conversations = db.query(Conversation).order_by(desc(Conversation.timestamp)).limit(10).all()
        recent_users = db.query(User).order_by(desc(User.created_at)).limit(10).all()
        recent_tasks = db.query(Task).order_by(desc(Task.created_at)).limit(10).all()
        
        logger.info("System stats retrieved successfully")
        return {
            "total_users": total_users,
            "total_conversations": total_conversations,
            "total_files": total_files,
            "total_tasks": total_tasks,
            "risk_distribution": risk_distribution,
            "role_distribution": role_distribution,
            "recent_conversations": [
                {
                    "id": conv.id,
                    "user_id": conv.user_id,
                    "input_type": conv.input_type,
                    "risk_level": conv.risk_level,
                    "timestamp": conv.timestamp.isoformat()
                } for conv in recent_conversations
            ],
            "recent_users": [
                {
                    "id": user.id,
                    "username": user.username,
                    "role": user.role,
                    "created_at": user.created_at.isoformat()
                } for user in recent_users
            ],
            "recent_tasks": [
                {
                    "id": task.id,
                    "task_type": task.task_type,
                    "status": task.status,
                    "priority": task.priority,
                    "created_at": task.created_at.isoformat()
                } for task in recent_tasks
            ]
        }
    except Exception as e:
        logger.error(f"System stats error: {str(e)}")
        raise HTTPException(status_code=500, detail="خطأ في الحصول على إحصائيات النظام")

# حذف محادثة
@app.delete("/delete_conversation/{conversation_id}")
def delete_conversation(
    conversation_id: int,
    Authorize: AuthJWT = Depends(),
    db: Session = Depends(get_db)
):
    """حذف محادثة"""
    try:
        Authorize.jwt_required()
        current_user = Authorize.get_jwt_subject()
        
        user = db.query(User).filter(User.username == current_user).first()
        if not user:
            raise HTTPException(status_code=401, detail="مستخدم غير مصرح به")
        
        conversation = db.query(Conversation).filter(
            Conversation.id == conversation_id,
            Conversation.user_id == user.id
        ).first()
        
        if not conversation:
            raise HTTPException(status_code=404, detail="المحادثة غير موجودة")
        
        db.delete(conversation)
        db.commit()
        
        logger.info(f"Conversation deleted: {conversation_id}")
        return {"message": "تم حذف المحادثة"}
    except Exception as e:
        logger.error(f"Delete conversation error: {str(e)}")
        db.rollback()
        raise HTTPException(status_code=500, detail="خطأ في حذف المحادثة")

# إنشاء نسخة احتياطية
@app.post("/create_backup")
def create_backup(db: Session = Depends(get_db)):
    """إنشاء نسخة احتياطية"""
    try:
        if not config.BACKUP_ENABLED:
            raise HTTPException(status_code=400, detail="النسخ الاحتياطي غير مفعل")
        
        backup_path = create_backup_path()
        
        # هنا يمكن إضافة كود لنسخ قاعدة البيانات
        logger.info(f"Backup created at: {backup_path}")
        return {
            "message": "تم إنشاء النسخة الاحتياطية",
            "backup_path": backup_path
        }
    except Exception as e:
        logger.error(f"Backup creation error: {str(e)}")
        raise HTTPException(status_code=500, detail="خطأ في إنشاء النسخة الاحتياطية")

# تحديث النظام
@app.post("/update_system")
def update_system():
    """تحديث النظام"""
    try:
        # هنا يمكن إضافة كود لتحديث النظام
        logger.info("System update initiated")
        return {"message": "تم بدء عملية التحديث"}
    except Exception as e:
        logger.error(f"System update error: {str(e)}")
        raise HTTPException(status_code=500, detail="خطأ في تحديث النظام")

# الحصول على معلومات النظام
@app.get("/system_info")
def get_system_info():
    """الحصول على معلومات النظام"""
    try:
        health = get_system_health()
        return {
            "version": "2.1",
            "environment": "production",
            "features": [
                "Multi-language support",
                "Secure authentication",
                "Database optimization",
                "Continuous learning",
                "Backup system",
                "Monitoring capabilities"
            ],
            "dependencies": [
                "FastAPI",
                "SQLAlchemy",
                "Transformers",
                "Whisper",
                "JWT Auth"
            ],
            "health": health
        }
    except Exception as e:
        logger.error(f"System info error: {str(e)}")
        raise HTTPException(status_code=500, detail="خطأ في الحصول على معلومات النظام")

# التحقق من حالة النظام
@app.get("/health")
def health_check():
    """فحص حالة النظام"""
    try:
        health = get_system_health()
        return {
            "status": "healthy",
            "timestamp": datetime.now().isoformat(),
            "service": "MyAIProject_v2",
            "health": health
        }
    except Exception as e:
        logger.error(f"Health check error: {str(e)}")
        return {
            "status": "unhealthy",
            "timestamp": datetime.now().isoformat(),
            "error": str(e)
        }

# الحصول على محادثات المستخدم
@app.get("/user/conversations")
def get_user_conversations(
    Authorize: AuthJWT = Depends(),
    db: Session = Depends(get_db),
    limit: int = 10,
    offset: int = 0
):
    """الحصول على محادثات المستخدم"""
    try:
        Authorize.jwt_required()
        current_user = Authorize.get_jwt_subject()
        
        user = db.query(User).filter(User.username == current_user).first()
        if not user:
            raise HTTPException(status_code=401, detail="مستخدم غير مصرح به")
        
        conversations = db.query(Conversation)\
            .filter(Conversation.user_id == user.id)\
            .order_by(desc(Conversation.timestamp))\
            .offset(offset)\
            .limit(limit)\
            .all()
        
        return {
            "conversations": [
                {
                    "id": conv.id,
                    "input_type": conv.input_type,
                    "input_content": conv.input_content[:100] + "...",
                    "output_content": conv.output_content[:100] + "...",
                    "risk_level": conv.risk_level,
                    "confidence_score": conv.confidence_score,
                    "timestamp": conv.timestamp.isoformat(),
                    "metadata_info": conv.metadata_info
                } for conv in conversations
            ],
            "total": len(conversations)
        }
    except Exception as e:
        logger.error(f"Get user conversations error: {str(e)}")
        raise HTTPException(status_code=500, detail="خطأ في الحصول على محادثات المستخدم")

# البحث في المحادثات
@app.get("/search/conversations")
def search_conversations(
    query: str,
    Authorize: AuthJWT = Depends(),
    db: Session = Depends(get_db),
    limit: int = 10
):
    """البحث في المحادثات"""
    try:
        Authorize.jwt_required()
        current_user = Authorize.get_jwt_subject()
        
        user = db.query(User).filter(User.username == current_user).first()
        if not user:
            raise HTTPException(status_code=401, detail="مستخدم غير مصرح به")
        
        # البحث في المحادثات
        conversations = db.query(Conversation)\
            .filter(
                and_(
                    Conversation.user_id == user.id,
                    or_(
                        Conversation.input_content.contains(query),
                        Conversation.output_content.contains(query),
                        Conversation.metadata_info.contains(query)
                    )
                )
            )\
            .order_by(desc(Conversation.timestamp))\
            .limit(limit)\
            .all()
        
        return {
            "conversations": [
                {
                    "id": conv.id,
                    "input_type": conv.input_type,
                    "input_content": conv.input_content[:100] + "...",
                    "output_content": conv.output_content[:100] + "...",
                    "risk_level": conv.risk_level,
                    "confidence_score": conv.confidence_score,
                    "timestamp": conv.timestamp.isoformat(),
                    "metadata_info": conv.metadata_info
                } for conv in conversations
            ],
            "total": len(conversations)
        }
    except Exception as e:
        logger.error(f"Search conversations error: {str(e)}")
        raise HTTPException(status_code=500, detail="خطأ في البحث في المحادثات")

@app.get("/")
def read_root():
    """الصفحة الرئيسية"""
    return {
        "message": "نظام الذكاء الاصطناعي MyAIProject_v2 شغال!",
        "version": "2.1",
        "features": [
            "تحليل النصوص",
            "تحليل الصور",
            "تحليل الصوت",
            "تحليل الملفات",
            "التعلم التراكمي",
            "نظام التحكم بالمستخدمين",
            "نظام المراقبة",
            "نظام النسخ الاحتياطي",
            "البحث والتحليل المتقدم"
        ],
        "status": "running"
    }

# نقطة نهاية لاختبار النظام
@app.get("/test")
def test_endpoint():
    """نقطة نهاية لاختبار النظام"""
    return {
        "message": "Test endpoint working!",
        "timestamp": datetime.now().isoformat()
    }