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() }