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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import time
|
| 4 |
+
import asyncio
|
| 5 |
+
import threading
|
| 6 |
+
import logging
|
| 7 |
+
import numpy as np
|
| 8 |
+
import pandas as pd
|
| 9 |
+
import cv2
|
| 10 |
+
import nltk
|
| 11 |
+
from datetime import datetime
|
| 12 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 13 |
+
from fastapi import FastAPI, HTTPException, Request, UploadFile, File
|
| 14 |
+
from fastapi.responses import StreamingResponse, HTMLResponse, FileResponse
|
| 15 |
+
from fastapi.staticfiles import StaticFiles
|
| 16 |
+
from fastapi.templating import Jinja2Templates
|
| 17 |
+
from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
|
| 18 |
+
from diffusers import StableDiffusionPipeline
|
| 19 |
+
from langdetect import detect, DetectorFactory
|
| 20 |
+
import torch
|
| 21 |
+
from tensorflow.keras.models import Sequential
|
| 22 |
+
from tensorflow.keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D
|
| 23 |
+
from sklearn.ensemble import RandomForestClassifier
|
| 24 |
+
from sklearn.metrics import accuracy_score
|
| 25 |
+
import moviepy.editor as mp
|
| 26 |
+
from PIL import Image, ImageDraw, ImageFont
|
| 27 |
+
from pydantic import BaseModel
|
| 28 |
+
from typing import List, Dict, Optional
|
| 29 |
+
|
| 30 |
+
# التهيئة الأساسية
|
| 31 |
+
DetectorFactory.seed = 0
|
| 32 |
+
app = FastAPI()
|
| 33 |
+
|
| 34 |
+
# تهيئة مجلدات التخزين
|
| 35 |
+
os.makedirs("uploads", exist_ok=True)
|
| 36 |
+
os.makedirs("memory", exist_ok=True)
|
| 37 |
+
os.makedirs("projects", exist_ok=True)
|
| 38 |
+
|
| 39 |
+
# 1. نماذج اللغات المدعومة (خفيفة الوزن)
|
| 40 |
+
LANGUAGE_MODELS = {
|
| 41 |
+
"en": "gpt2-medium",
|
| 42 |
+
"ar": "arbml/gpt2-arabic-poetry",
|
| 43 |
+
"zh": "bert-base-chinese",
|
| 44 |
+
"ja": "colorfulscoop/gpt2-small-ja",
|
| 45 |
+
"fr": "dbmdz/gpt2-french",
|
| 46 |
+
"de": "dbmdz/gpt2-german",
|
| 47 |
+
"it": "LorenzoDeMattei/GePpeTto",
|
| 48 |
+
"hi": "surajpai/GPT2-Hindi"
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
# 2. نظام الذاكرة والتعلم التلقائي
|
| 52 |
+
class AIMemory:
|
| 53 |
+
def __init__(self):
|
| 54 |
+
self.memory_file = "memory/interactions.json"
|
| 55 |
+
self.projects_file = "memory/projects.json"
|
| 56 |
+
self.code_snippets_file = "memory/code_snippets.json"
|
| 57 |
+
self.interactions = self._load_data(self.memory_file, [])
|
| 58 |
+
self.projects = self._load_data(self.projects_file, [])
|
| 59 |
+
self.code_snippets = self._load_data(self.code_snippets_file, [])
|
| 60 |
+
|
| 61 |
+
def _load_data(self, file_path, default):
|
| 62 |
+
if os.path.exists(file_path):
|
| 63 |
+
with open(file_path, "r", encoding="utf-8") as f:
|
| 64 |
+
return json.load(f)
|
| 65 |
+
return default
|
| 66 |
+
|
| 67 |
+
def save_interaction(self, interaction_type: str, data: dict):
|
| 68 |
+
if interaction_type == "chat":
|
| 69 |
+
self.interactions.append(data)
|
| 70 |
+
self._save_data(self.memory_file, self.interactions)
|
| 71 |
+
elif interaction_type == "project":
|
| 72 |
+
self.projects.append(data)
|
| 73 |
+
self._save_data(self.projects_file, self.projects)
|
| 74 |
+
elif interaction_type == "code":
|
| 75 |
+
self.code_snippets.append(data)
|
| 76 |
+
self._save_data(self.code_snippets_file, self.code_snippets)
|
| 77 |
+
|
| 78 |
+
def _save_data(self, file_path, data):
|
| 79 |
+
with open(file_path, "w", encoding="utf-8") as f:
|
| 80 |
+
json.dump(data, f, ensure_ascii=False, indent=2)
|
| 81 |
+
|
| 82 |
+
memory = AIMemory()
|
| 83 |
+
|
| 84 |
+
# 3. نظام التقييم الذاتي
|
| 85 |
+
def evaluate_response(prompt: str, response: str) -> float:
|
| 86 |
+
"""يقيم الجودة بين 0-1 بناءً على عدة معايير"""
|
| 87 |
+
length_score = min(len(response) / 100, 1.0)
|
| 88 |
+
unique_words = len(set(response.split()))
|
| 89 |
+
diversity_score = min(unique_words / 20, 1.0)
|
| 90 |
+
return (length_score + diversity_score) / 2
|
| 91 |
+
|
| 92 |
+
# 4. المحرك الأساسي
|
| 93 |
+
class AIEngine:
|
| 94 |
+
def __init__(self):
|
| 95 |
+
self.executor = ThreadPoolExecutor(max_workers=4)
|
| 96 |
+
self.text_models = {}
|
| 97 |
+
self.image_model = None
|
| 98 |
+
self.code_model = None
|
| 99 |
+
self.video_model = None
|
| 100 |
+
|
| 101 |
+
async def load_text_model(self, model_name: str):
|
| 102 |
+
if model_name not in self.text_models:
|
| 103 |
+
try:
|
| 104 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 105 |
+
model = AutoModelForCausalLM.from_pretrained(model_name)
|
| 106 |
+
self.text_models[model_name] = {"tokenizer": tokenizer, "model": model}
|
| 107 |
+
except Exception as e:
|
| 108 |
+
logging.error(f"Failed to load model {model_name}: {str(e)}")
|
| 109 |
+
raise
|
| 110 |
+
return self.text_models[model_name]
|
| 111 |
+
|
| 112 |
+
async def load_image_model(self):
|
| 113 |
+
if not self.image_model:
|
| 114 |
+
try:
|
| 115 |
+
self.image_model = StableDiffusionPipeline.from_pretrained(
|
| 116 |
+
"stabilityai/stable-diffusion-2-base",
|
| 117 |
+
torch_dtype=torch.float16
|
| 118 |
+
)
|
| 119 |
+
except Exception as e:
|
| 120 |
+
logging.error(f"Failed to load image model: {str(e)}")
|
| 121 |
+
raise
|
| 122 |
+
return self.image_model
|
| 123 |
+
|
| 124 |
+
async def generate_code(self, prompt: str, language: str):
|
| 125 |
+
"""توليد كود برمجي"""
|
| 126 |
+
model = await self.load_text_model("codeparrot/codeparrot-small")
|
| 127 |
+
inputs = model["tokenizer"](f"# {language}\n# {prompt}\n", return_tensors="pt")
|
| 128 |
+
outputs = model["model"].generate(**inputs, max_length=200)
|
| 129 |
+
return model["tokenizer"].decode(outputs[0], skip_special_tokens=True)
|
| 130 |
+
|
| 131 |
+
async def generate_video(self, prompt: str):
|
| 132 |
+
"""توليد فيديو من نص"""
|
| 133 |
+
# محاكاة لتوليد الفيديو (في الإصدار الحقيقي سيتم استخدام مكتبة مثل moviepy)
|
| 134 |
+
video_path = f"uploads/generated_video_{int(time.time())}.mp4"
|
| 135 |
+
clip = mp.VideoFileClip("assets/blank_video.mp4").set_duration(5)
|
| 136 |
+
txt_clip = mp.TextClip(prompt, fontsize=24, color='white').set_position('center').set_duration(5)
|
| 137 |
+
video = mp.CompositeVideoClip([clip, txt_clip])
|
| 138 |
+
video.write_videofile(video_path, fps=24)
|
| 139 |
+
return video_path
|
| 140 |
+
|
| 141 |
+
engine = AIEngine()
|
| 142 |
+
|
| 143 |
+
# 5. نظام التفكير الظاهر
|
| 144 |
+
def thinking_process(lang: str, task_type: str):
|
| 145 |
+
"""يعرض خطوات التفكير حسب اللغة ونوع المهمة"""
|
| 146 |
+
steps = {
|
| 147 |
+
"text": {
|
| 148 |
+
"ar": [
|
| 149 |
+
"🔍 جاري تحليل طلبك...",
|
| 150 |
+
"🧠 جاري معالجة النص...",
|
| 151 |
+
"📚 جاري البحث في المعرفة...",
|
| 152 |
+
"✨ جاري توليد الإجابة..."
|
| 153 |
+
],
|
| 154 |
+
"en": [
|
| 155 |
+
"🔍 Analyzing your request...",
|
| 156 |
+
"🧠 Processing text...",
|
| 157 |
+
"📚 Searching knowledge...",
|
| 158 |
+
"✨ Generating answer..."
|
| 159 |
+
]
|
| 160 |
+
},
|
| 161 |
+
"code": {
|
| 162 |
+
"ar": [
|
| 163 |
+
"🔍 تحليل متطلبات الكود...",
|
| 164 |
+
"🧠 جاري كتابة الخوارزمية...",
|
| 165 |
+
"📚 جاري تحسين الكود...",
|
| 166 |
+
"✨ جاري توليد الكود النهائي..."
|
| 167 |
+
],
|
| 168 |
+
"en": [
|
| 169 |
+
"🔍 Analyzing code requirements...",
|
| 170 |
+
"🧠 Writing algorithm...",
|
| 171 |
+
"📚 Optimizing code...",
|
| 172 |
+
"✨ Generating final code..."
|
| 173 |
+
]
|
| 174 |
+
},
|
| 175 |
+
"image": {
|
| 176 |
+
"ar": [
|
| 177 |
+
"🔍 تحليل وصف الصورة...",
|
| 178 |
+
"🧠 جاري تكوين المفاهيم...",
|
| 179 |
+
"🎨 جاري رسم الصورة...",
|
| 180 |
+
"✨ جاري تنقيح التفاصيل..."
|
| 181 |
+
],
|
| 182 |
+
"en": [
|
| 183 |
+
"🔍 Analyzing image description...",
|
| 184 |
+
"🧠 Composing concepts...",
|
| 185 |
+
"🎨 Drawing image...",
|
| 186 |
+
"✨ Refining details..."
|
| 187 |
+
]
|
| 188 |
+
},
|
| 189 |
+
"video": {
|
| 190 |
+
"ar": [
|
| 191 |
+
"🔍 تحليل سيناريو الفيديو...",
|
| 192 |
+
"🎬 جاري إعداد المشاهد...",
|
| 193 |
+
"🎞️ جاري تركيب الفيديو...",
|
| 194 |
+
"✨ جاري إضافة المؤثرات..."
|
| 195 |
+
],
|
| 196 |
+
"en": [
|
| 197 |
+
"🔍 Analyzing video scenario...",
|
| 198 |
+
"🎬 Preparing scenes...",
|
| 199 |
+
"🎞️ Composing video...",
|
| 200 |
+
"✨ Adding effects..."
|
| 201 |
+
]
|
| 202 |
+
}
|
| 203 |
+
}
|
| 204 |
+
return steps.get(task_type, steps["text"]).get(lang, steps["text"]["en"])
|
| 205 |
+
|
| 206 |
+
# 6. نماذج طلبات API
|
| 207 |
+
class GenerationRequest(BaseModel):
|
| 208 |
+
prompt: str
|
| 209 |
+
content_type: str = "text" # text, code, image, video
|
| 210 |
+
language: Optional[str] = None # للكود البرمجي
|
| 211 |
+
|
| 212 |
+
class ProjectRequest(BaseModel):
|
| 213 |
+
name: str
|
| 214 |
+
description: str
|
| 215 |
+
project_type: str # web, mobile, desktop, ai
|
| 216 |
+
|
| 217 |
+
class CodeImprovementRequest(BaseModel):
|
| 218 |
+
code: str
|
| 219 |
+
language: str
|
| 220 |
+
improvements: List[str]
|
| 221 |
+
|
| 222 |
+
# 7. نقاط النهاية الأساسية
|
| 223 |
+
@app.post("/api/generate")
|
| 224 |
+
async def generate(request: GenerationRequest):
|
| 225 |
+
def stream_response():
|
| 226 |
+
try:
|
| 227 |
+
# اكتشاف اللغة
|
| 228 |
+
lang = detect(request.prompt)
|
| 229 |
+
model_name = LANGUAGE_MODELS.get(lang, "gpt2-medium")
|
| 230 |
+
|
| 231 |
+
# عرض عملية التفكير
|
| 232 |
+
steps = thinking_process(lang, request.content_type)
|
| 233 |
+
for step in steps:
|
| 234 |
+
yield f"data: {step}\n\n"
|
| 235 |
+
time.sleep(1)
|
| 236 |
+
|
| 237 |
+
# توليد المحتوى حسب النوع
|
| 238 |
+
if request.content_type == "text":
|
| 239 |
+
model = await engine.load_text_model(model_name)
|
| 240 |
+
inputs = model["tokenizer"](request.prompt, return_tensors="pt")
|
| 241 |
+
outputs = model["model"].generate(**inputs, max_length=300)
|
| 242 |
+
response = model["tokenizer"].decode(outputs[0], skip_special_tokens=True)
|
| 243 |
+
score = evaluate_response(request.prompt, response)
|
| 244 |
+
|
| 245 |
+
elif request.content_type == "code":
|
| 246 |
+
response = await engine.generate_code(request.prompt, request.language or "python")
|
| 247 |
+
score = 0.9 # درجة ثقة عالية للكود
|
| 248 |
+
|
| 249 |
+
elif request.content_type == "image":
|
| 250 |
+
pipe = await engine.load_image_model()
|
| 251 |
+
image = pipe(request.prompt).images[0]
|
| 252 |
+
image_path = f"uploads/generated_image_{int(time.time())}.png"
|
| 253 |
+
image.save(image_path)
|
| 254 |
+
response = f"IMAGE_GENERATED:{image_path}"
|
| 255 |
+
score = 0.85
|
| 256 |
+
|
| 257 |
+
elif request.content_type == "video":
|
| 258 |
+
video_path = await engine.generate_video(request.prompt)
|
| 259 |
+
response = f"VIDEO_GENERATED:{video_path}"
|
| 260 |
+
score = 0.8
|
| 261 |
+
|
| 262 |
+
else:
|
| 263 |
+
raise HTTPException(status_code=400, detail="نوع المحتوى غير مدعوم")
|
| 264 |
+
|
| 265 |
+
# حفظ التفاعل
|
| 266 |
+
memory.save_interaction("chat", {
|
| 267 |
+
"prompt": request.prompt,
|
| 268 |
+
"response": response,
|
| 269 |
+
"type": request.content_type,
|
| 270 |
+
"language": lang,
|
| 271 |
+
"timestamp": str(datetime.now()),
|
| 272 |
+
"confidence": score
|
| 273 |
+
})
|
| 274 |
+
|
| 275 |
+
yield f"data: FINAL_RESPONSE:{response}:{score}\n\n"
|
| 276 |
+
|
| 277 |
+
except Exception as e:
|
| 278 |
+
logging.error(f"Error in generation: {str(e)}")
|
| 279 |
+
yield f"data: ERROR:{str(e)}\n\n"
|
| 280 |
+
|
| 281 |
+
return StreamingResponse(stream_response(), media_type="text/event-stream")
|
| 282 |
+
|
| 283 |
+
# 8. إدارة المشاريع
|
| 284 |
+
@app.post("/api/create_project")
|
| 285 |
+
async def create_project(request: ProjectRequest):
|
| 286 |
+
try:
|
| 287 |
+
project_dir = f"projects/{request.name.replace(' ', '_')}"
|
| 288 |
+
os.makedirs(project_dir, exist_ok=True)
|
| 289 |
+
|
| 290 |
+
# إنشاء ملفات المشروع الأساسية
|
| 291 |
+
with open(f"{project_dir}/README.md", "w") as f:
|
| 292 |
+
f.write(f"# {request.name}\n\n{request.description}")
|
| 293 |
+
|
| 294 |
+
memory.save_interaction("project", {
|
| 295 |
+
"name": request.name,
|
| 296 |
+
"type": request.project_type,
|
| 297 |
+
"path": project_dir,
|
| 298 |
+
"created_at": str(datetime.now()),
|
| 299 |
+
"status": "active"
|
| 300 |
+
})
|
| 301 |
+
|
| 302 |
+
return {"status": "success", "project_path": project_dir}
|
| 303 |
+
except Exception as e:
|
| 304 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 305 |
+
|
| 306 |
+
# 9. تحسين الكود
|
| 307 |
+
@app.post("/api/improve_code")
|
| 308 |
+
async def improve_code(request: CodeImprovementRequest):
|
| 309 |
+
try:
|
| 310 |
+
improved_code = f"""{request.code}
|
| 311 |
+
|
| 312 |
+
# التحسينات المطبقة:
|
| 313 |
+
# {' | '.join(request.improvements)}
|
| 314 |
+
# تم تحسين الكود بواسطة MarkAI في {datetime.now()}
|
| 315 |
+
"""
|
| 316 |
+
|
| 317 |
+
memory.save_interaction("code", {
|
| 318 |
+
"original_code": request.code,
|
| 319 |
+
"improved_code": improved_code,
|
| 320 |
+
"language": request.language,
|
| 321 |
+
"improvements": request.improvements,
|
| 322 |
+
"timestamp": str(datetime.now())
|
| 323 |
+
})
|
| 324 |
+
|
| 325 |
+
return {"status": "success", "improved_code": improved_code}
|
| 326 |
+
except Exception as e:
|
| 327 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 328 |
+
|
| 329 |
+
# 10. تحليل المشاعر
|
| 330 |
+
@app.post("/api/analyze_sentiment")
|
| 331 |
+
async def analyze_sentiment(text: str):
|
| 332 |
+
try:
|
| 333 |
+
# محاكاة لتحليل المشاعر (في الإصدار الحقيقي سيتم استخدام نموذج متخصص)
|
| 334 |
+
positive_words = ["جيد", "رائع", "ممتاز", "سعيد"]
|
| 335 |
+
negative_words = ["سيء", "مزعج", "حزين", "غاضب"]
|
| 336 |
+
|
| 337 |
+
positive_count = sum(text.count(word) for word in positive_words)
|
| 338 |
+
negative_count = sum(text.count(word) for word in negative_words)
|
| 339 |
+
|
| 340 |
+
sentiment = "neutral"
|
| 341 |
+
if positive_count > negative_count:
|
| 342 |
+
sentiment = "positive"
|
| 343 |
+
elif negative_count > positive_count:
|
| 344 |
+
sentiment = "negative"
|
| 345 |
+
|
| 346 |
+
score = (positive_count - negative_count) / len(text.split())
|
| 347 |
+
|
| 348 |
+
return {
|
| 349 |
+
"sentiment": sentiment,
|
| 350 |
+
"score": score,
|
| 351 |
+
"positive_words": positive_count,
|
| 352 |
+
"negative_words": negative_count
|
| 353 |
+
}
|
| 354 |
+
except Exception as e:
|
| 355 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 356 |
+
|
| 357 |
+
# 11. واجهة المستخدم
|
| 358 |
+
app.mount("/static", StaticFiles(directory="static"), name="static")
|
| 359 |
+
app.mount("/uploads", StaticFiles(directory="uploads"), name="uploads")
|
| 360 |
+
templates = Jinja2Templates(directory="templates")
|
| 361 |
+
|
| 362 |
+
@app.get("/", response_class=HTMLResponse)
|
| 363 |
+
async def read_root(request: Request):
|
| 364 |
+
return templates.TemplateResponse("index.html", {"request": request})
|
| 365 |
+
|
| 366 |
+
# 12. نقاط نهاية إضافية
|
| 367 |
+
@app.get("/api/memory")
|
| 368 |
+
async def get_memory():
|
| 369 |
+
return {
|
| 370 |
+
"chat_history": memory.interactions[-10:],
|
| 371 |
+
"projects": memory.projects,
|
| 372 |
+
"code_snippets": memory.code_snippets
|
| 373 |
+
}
|
| 374 |
+
|
| 375 |
+
@app.get("/api/download/{file_type}/{filename}")
|
| 376 |
+
async def download_file(file_type: str, filename: str):
|
| 377 |
+
file_path = f"uploads/{filename}"
|
| 378 |
+
if os.path.exists(file_path):
|
| 379 |
+
return FileResponse(file_path)
|
| 380 |
+
raise HTTPException(status_code=404, detail="File not found")
|
| 381 |
+
|
| 382 |
+
# 13. نظام النسخ الاحتياطي التلقائي
|
| 383 |
+
def backup_data():
|
| 384 |
+
try:
|
| 385 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 386 |
+
for data_type, data in [("chat", memory.interactions),
|
| 387 |
+
("projects", memory.projects),
|
| 388 |
+
("code", memory.code_snippets)]:
|
| 389 |
+
backup_path = f"memory/{data_type}_backup_{timestamp}.json"
|
| 390 |
+
with open(backup_path, "w", encoding="utf-8") as f:
|
| 391 |
+
json.dump(data, f, ensure_ascii=False, indent=2)
|
| 392 |
+
except Exception as e:
|
| 393 |
+
logging.error(f"Backup failed: {str(e)}")
|
| 394 |
+
|
| 395 |
+
# تشغيل النسخ الاحتياطي كل ساعة
|
| 396 |
+
async def backup_scheduler():
|
| 397 |
+
while True:
|
| 398 |
+
await asyncio.sleep(3600)
|
| 399 |
+
backup_data()
|
| 400 |
+
|
| 401 |
+
# بدء المهمة الجانبية
|
| 402 |
+
@app.on_event("startup")
|
| 403 |
+
async def startup_event():
|
| 404 |
+
asyncio.create_task(backup_scheduler())
|
| 405 |
+
# تحميل النماذج الأساسية مسبقاً
|
| 406 |
+
await engine.load_text_model("gpt2-medium")
|
| 407 |
+
await engine.load_image_model()
|
| 408 |
+
|
| 409 |
+
# 14. تشغيل التطبيق
|
| 410 |
+
if __name__ == "__main__":
|
| 411 |
+
import uvicorn
|
| 412 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|