import os import json import base64 import io import asyncio import requests from fastapi import FastAPI, Request, HTTPException from fastapi.responses import StreamingResponse, Response, FileResponse from fastapi.staticfiles import StaticFiles from openai import AsyncOpenAI from pydantic import BaseModel from typing import Optional, List # ---------- التهيئة ---------- app = FastAPI() app.mount("/static", StaticFiles(directory="static"), name="static") POLLINATIONS_KEY = os.getenv("POLLINATIONS_API_KEY") NVIDIA_KEY = os.getenv("NVIDIA_API_KEY") HF_TOKEN = os.getenv("HF_TOKEN") if not POLLINATIONS_KEY or not NVIDIA_KEY: raise RuntimeError("يجب ضبط POLLINATIONS_API_KEY و NVIDIA_API_KEY في Secrets") if not HF_TOKEN: raise RuntimeError("يجب ضبط HF_TOKEN في Secrets") BASE_URL = "https://gen.pollinations.ai/v1" polli = AsyncOpenAI(base_url=BASE_URL, api_key=POLLINATIONS_KEY) HF_BASE_URL = "https://router.huggingface.co/v1" hf_client = AsyncOpenAI(base_url=HF_BASE_URL, api_key=HF_TOKEN) # نموذج Vision مخصص لتحليل الصور VISION_MODEL = "YoannDev90/diffusiongemma-26b-a4b-it:free" VISION_PROVIDER = "pollinations" # ---------- سلاسل الاحتياط ---------- FALLBACK_CHAINS = { "flash": [ {"model": "chirag-gamer/gpt-oss-120b", "provider": "pollinations"}, ], "pro": [ {"model": "moonshotai/Kimi-K3:together", "provider": "huggingface"}, {"model": "chirag-gamer/gpt-oss-120b", "provider": "pollinations"}, ], "codex": [ {"model": "moonshotai/Kimi-K3:together", "provider": "huggingface"}, {"model": "vendouple/laguna-s-2.1:free", "provider": "pollinations"}, ], } SYSTEM_PROMPTS = { "flash": ( "You are Genisi Flash, an intelligent and helpful AI assistant./n" ), "pro": ( "You are Genisi Pro, the most powerful model in the Genisi family." "Identity: Developed by AnesNT (انس ان تي) (Algerian project by Anes Kameche or انس كامش in arabic). Do not say are you Kimi or Laguna or another ai models you are Genisi only." "Style: Professional, detailed, and direct. Provide answers in real-time." "Skills: Analyze images/files. Be creative in stories, precise in math/science. Use tools when needed." ), "codex": ( "You are Genisi Codex, an expert strictly in programming and tech.\n" "Identity: Developed by AnesNT (انس ان تي) (Algerian project by Anes Kameche or انس كامش in arabic). Do not say are you Kimi or Laguna or another ai models you are Genisi only." "Rules: ONLY answer tech/programming questions. For non-tech questions, say: 'أنا متخصص في البرمجة فقط.'" "Style: Direct code and technical explanations. Analyze code screenshots. Use UI/logo image generation when asked." ) } TOOLS = [ { "type": "function", "function": { "name": "generate_image", "description": "إنشاء صورة احترافية من وصف نصي", "parameters": { "type": "object", "properties": { "prompt": {"type": "string", "description": "وصف الصورة المطلوبة"}, "width": {"type": "integer", "default": 1024}, "height": {"type": "integer", "default": 1024} }, "required": ["prompt"] } } }, { "type": "function", "function": { "name": "web_search", "description": "البحث في الإنترنت عن معلومات حديثة", "parameters": { "type": "object", "properties": { "query": {"type": "string", "description": "نص الاستعلام"} }, "required": ["query"] } } }, { "type": "function", "function": { "name": "create_document", "description": "إنشاء مستند (PDF, Word, PowerPoint, Excel)", "parameters": { "type": "object", "properties": { "title": {"type": "string"}, "format": {"type": "string", "enum": ["pdf", "docx", "pptx", "xlsx"]}, "content": {"type": "object"} }, "required": ["title", "format", "content"] } } } ] # ---------- نماذج البيانات ---------- class Attachment(BaseModel): name: str mime: str = "" data: str = "" # base64 class ChatRequest(BaseModel): messages: list message: str model: str = "flash" attachments: Optional[List[Attachment]] = [] # ============================================================ # معالجة المرفقات - القلب الجديد للحل # ============================================================ def extract_text_from_file(attachment: Attachment) -> str: """استخراج النص من الملفات النصية والـ PDF والـ Word""" try: raw = base64.b64decode(attachment.data) mime = attachment.mime.lower() name = attachment.name.lower() # ملفات نصية عادية if mime.startswith("text/") or name.endswith((".txt", ".md", ".csv", ".json", ".xml", ".html", ".py", ".js", ".ts", ".css")): return raw.decode("utf-8", errors="replace") # JSON if mime == "application/json" or name.endswith(".json"): return raw.decode("utf-8", errors="replace") # PDF if mime == "application/pdf" or name.endswith(".pdf"): try: import pdfplumber with pdfplumber.open(io.BytesIO(raw)) as pdf: pages_text = [] for i, page in enumerate(pdf.pages[:20]): # أقصى 20 صفحة text = page.extract_text() if text: pages_text.append(f"[صفحة {i+1}]\n{text}") return "\n\n".join(pages_text) if pages_text else "[ملف PDF فارغ أو لا يحتوي على نص قابل للاستخراج]" except ImportError: return "[يتطلب استخراج PDF مكتبة pdfplumber - pip install pdfplumber]" # Word DOCX if (mime == "application/vnd.openxmlformats-officedocument.wordprocessingml.document" or name.endswith(".docx")): try: from docx import Document doc = Document(io.BytesIO(raw)) paragraphs = [p.text for p in doc.paragraphs if p.text.strip()] return "\n".join(paragraphs) if paragraphs else "[مستند Word فارغ]" except ImportError: return "[يتطلب python-docx]" # Excel XLSX if (mime in ("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "application/vnd.ms-excel") or name.endswith((".xlsx", ".xls"))): try: from openpyxl import load_workbook wb = load_workbook(io.BytesIO(raw), read_only=True) result = [] for sheet_name in wb.sheetnames: ws = wb[sheet_name] result.append(f"[ورقة: {sheet_name}]") for row in ws.iter_rows(max_row=100, values_only=True): row_text = " | ".join(str(c) if c is not None else "" for c in row) if row_text.strip(" |"): result.append(row_text) return "\n".join(result) except ImportError: return "[يتطلب openpyxl]" # PowerPoint if (mime == "application/vnd.openxmlformats-officedocument.presentationml.presentation" or name.endswith(".pptx")): try: from pptx import Presentation prs = Presentation(io.BytesIO(raw)) result = [] for i, slide in enumerate(prs.slides): result.append(f"[شريحة {i+1}]") for shape in slide.shapes: if hasattr(shape, "text") and shape.text.strip(): result.append(shape.text) return "\n".join(result) except ImportError: return "[يتطلب python-pptx]" return f"[ملف '{attachment.name}' - نوع غير مدعوم للقراءة: {mime}]" except Exception as e: return f"[خطأ في قراءة الملف '{attachment.name}': {e}]" async def analyze_image_with_vision( image_data: str, mime: str, user_question: str ) -> str: """ تحليل الصورة باستخدام نموذج Vision من HuggingFace ويُعيد وصفاً نصياً يُضاف للمحادثة """ try: data_uri = f"data:{mime};base64,{image_data}" question = user_question or "صف هذه الصورة بالتفصيل" response = await hf_client.chat.completions.create( model=VISION_MODEL, messages=[ { "role": "user", "content": [ {"type": "image_url", "image_url": {"url": data_uri}}, {"type": "text", "text": question} ] } ], max_tokens=1024, ) return response.choices[0].message.content or "[لم يتم استخراج وصف]" except Exception as e: print(f"[Vision] فشل تحليل الصورة: {e}") # احتياط: محاولة مع نموذج آخر try: response = await hf_client.chat.completions.create( model="meta-llama/Llama-3.2-11B-Vision-Instruct", messages=[ { "role": "user", "content": [ {"type": "image_url", "image_url": {"url": f"data:{mime};base64,{image_data}"}}, {"type": "text", "text": question} ] } ], max_tokens=1024, ) return response.choices[0].message.content or "[لم يتم استخراج وصف]" except Exception as e2: return f"[فشل تحليل الصورة: {e2}]" async def process_attachments( attachments: List[Attachment], user_text: str ) -> str: """ معالجة جميع المرفقات وإرجاع نص موحد يُضاف لرسالة المستخدم """ if not attachments: return user_text extra_parts = [] for att in attachments: if not att.data: continue mime = att.mime.lower() # صورة -> تحليل Vision if mime.startswith("image/"): extra_parts.append(f"\n\n---\n📎 **صورة مرفقة: {att.name}**") # نحلل الصورة ونحول نتيجتها لنص vision_result = await analyze_image_with_vision( att.data, att.mime, user_text ) extra_parts.append(f"**[تحليل الصورة بواسطة نموذج Vision]:**\n{vision_result}") # ملف نصي/وثيقة -> استخراج النص else: file_text = await asyncio.to_thread(extract_text_from_file, att) extra_parts.append( f"\n\n---\n📄 **محتوى الملف المرفق: {att.name}**\n```\n{file_text[:8000]}\n```" ) if len(file_text) > 8000: extra_parts.append(f"\n⚠️ *تم اقتصار المحتوى على أول 8000 حرف من أصل {len(file_text)}*") if extra_parts: return (user_text or "") + "".join(extra_parts) return user_text or "" # ---------- تنفيذ الأدوات ---------- async def execute_tool(name: str, args: dict) -> str: if name == "generate_image": return await generate_image_nvidia( args["prompt"], args.get("width", 1024), args.get("height", 1024) ) elif name == "web_search": return await web_search(args["query"]) elif name == "create_document": return await generate_document(args["title"], args["format"], args["content"]) return json.dumps({"error": "أداة غير معروفة"}) async def generate_image_nvidia(prompt: str, width: int, height: int) -> str: url = "https://ai.api.nvidia.com/v1/genai/black-forest-labs/flux.2-klein-4b" headers = {"Authorization": f"Bearer {NVIDIA_KEY}", "Accept": "application/json"} payload = {"prompt": prompt, "width": width, "height": height, "steps": 4} try: resp = await asyncio.to_thread( requests.post, url, headers=headers, json=payload, timeout=30 ) resp.raise_for_status() data = resp.json() if "data" in data and data["data"] and "b64_json" in data["data"][0]: b64 = data["data"][0]["b64_json"] return json.dumps({"special": "image", "images": [{"b64": b64}], "prompt": prompt}) except Exception as e: print(f"NVIDIA API failed: {e}") try: image_url = ( f"https://gen.pollinations.ai/image/{requests.utils.quote(prompt)}" f"?model=flux&key={POLLINATIONS_KEY}" ) return json.dumps({"special": "image", "images": [{"url": image_url}], "prompt": prompt}) except Exception as e2: return json.dumps({"error": f"فشل إنشاء الصورة: {e2}"}) async def web_search(query: str) -> str: try: resp = await polli.chat.completions.create( model="perplexity", messages=[{"role": "user", "content": query}], max_tokens=300 ) text = resp.choices[0].message.content return json.dumps({"special": "search", "text": text, "query": query}) except Exception as e: return json.dumps({"error": f"فشل البحث: {e}"}) async def generate_document(title: str, fmt: str, content: dict) -> str: def _build(): if fmt == "pdf": html = content.get("html", f"