Spaces:
Sleeping
Sleeping
Download app.py from Cyber00100ai/33ARISE: direct link, hf CLI and curl.
- Browser
- Download file 14.9 kB
-
https://huggingface.co/spaces/Cyber00100ai/33ARISE/resolve/main/app.py
- Command line
-
hf download hf://spaces/Cyber00100ai/33ARISE/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Cyber00100ai/33ARISE/resolve/main/app.py
14.9 kB
| import os | |
| import json | |
| import re | |
| import hashlib | |
| import sqlite3 | |
| from datetime import datetime, timedelta | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| import torch | |
| from fastapi import FastAPI, HTTPException | |
| from fastapi.responses import HTMLResponse, JSONResponse | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from pydantic import BaseModel | |
| from typing import Optional | |
| app = FastAPI(title="ARISE Shadow Guide") | |
| # Enable CORS | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| # --------- قاعدة البيانات (SQL Database) --------- | |
| DB_PATH = "/data/arise_shadow.db" | |
| def init_db(): | |
| try: | |
| os.makedirs("/data", exist_ok=True) | |
| conn = sqlite3.connect(DB_PATH) | |
| cursor = conn.cursor() | |
| cursor.execute('''CREATE TABLE IF NOT EXISTS users ( | |
| username TEXT PRIMARY KEY, | |
| password TEXT NOT NULL, | |
| created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP | |
| )''') | |
| cursor.execute('''CREATE TABLE IF NOT EXISTS progress ( | |
| hunter_id TEXT PRIMARY KEY, | |
| gold INTEGER DEFAULT 0, | |
| level INTEGER DEFAULT 1, | |
| exp INTEGER DEFAULT 0, | |
| last_sync TIMESTAMP DEFAULT CURRENT_TIMESTAMP, | |
| FOREIGN KEY (hunter_id) REFERENCES users (username) | |
| )''') | |
| conn.commit() | |
| conn.close() | |
| except Exception as e: | |
| print(f"DB Init Error: {e}") | |
| init_db() | |
| def hash_password(password: str): | |
| return hashlib.sha256(password.encode()).hexdigest() | |
| # --------- إعدادات النظام (System Config) --------- | |
| MODEL_NAME = "Qwen/Qwen2.5-0.5B-Instruct" | |
| print(f"Loading {MODEL_NAME} via Transformers...") | |
| try: | |
| tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME) | |
| model = AutoModelForCausalLM.from_pretrained( | |
| MODEL_NAME, | |
| torch_dtype="auto", | |
| device_map="auto" | |
| ) | |
| print("Shadow Monarch's Wisdom Loaded (Qwen 0.5B)!") | |
| except Exception as e: | |
| print(f"Error loading model: {e}") | |
| model = None | |
| tokenizer = None | |
| # --------- الذاكرة الديناميكية (Memory System) --------- | |
| CONVERSATION_MEMORY = {} | |
| def clean_memory(): | |
| now = datetime.now() | |
| keys_to_delete = [k for k, v in CONVERSATION_MEMORY.items() if now - v.get("last_updated", now) > timedelta(days=7)] | |
| for k in keys_to_delete: del CONVERSATION_MEMORY[k] | |
| def get_system_prompt(custom_persona: str = ""): | |
| if custom_persona and len(custom_persona.strip()) > 3: | |
| return f"التعليمات السيادية القاطعة: أنت محرك وعي اصطناعي فائق. ممنوع منعاً باتاً التحدث بأي لغة غير العربية. تقمص الشخصية التالية بدقة مطلقة:\n{custom_persona}" | |
| try: | |
| if os.path.exists("igris_persona.txt"): | |
| with open("igris_persona.txt", "r", encoding="utf-8") as f: | |
| return f.read() | |
| except: pass | |
| return "[النظام: إغريس ⚡]: مرشدك في رحلة الترقية. تحدث بالعربية فقط." | |
| def query_ai(user_message: str, system_prompt: str = "", hunter_id: str = "guest", is_json: bool = False) -> str: | |
| if model is None: return "عذرأ، النظام في وضع السكون." | |
| clean_memory() | |
| messages = [] | |
| # Force Arabic constraint even harder | |
| arabic_constraint = "\n\n[STRICT RULE: YOU MUST REPLY ONLY IN ARABIC. NO ENGLISH ALLOWED. NO EXCEPTIONS.]" | |
| final_system = (system_prompt + arabic_constraint) if system_prompt else arabic_constraint | |
| messages.append({"role": "system", "content": final_system}) | |
| if is_json: | |
| messages.append({"role": "user", "content": user_message}) | |
| else: | |
| user_mem = CONVERSATION_MEMORY.setdefault(hunter_id, {"history": [], "last_updated": datetime.now()}) | |
| for mem_msg in user_mem["history"][-6:]: messages.append(mem_msg) | |
| messages.append({"role": "user", "content": user_message}) | |
| try: | |
| text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) | |
| model_inputs = tokenizer([text], return_tensors="pt").to(model.device) | |
| generated_ids = model.generate(**model_inputs, max_new_tokens=256, temperature=0.7, pad_token_id=tokenizer.eos_token_id) | |
| generated_ids = [output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)] | |
| response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0].strip() | |
| # Arabic Filter: If it somehow replies in English (hallucination), we can catch it. | |
| # But for now, prompt engineering is usually enough for Qwen. | |
| if not is_json: | |
| user_mem["history"].extend([{"role": "user", "content": user_message}, {"role": "assistant", "content": response}]) | |
| user_mem["last_updated"] = datetime.now() | |
| return response | |
| except Exception as e: | |
| print(f"AI ERR: {e}") | |
| return "اضطراب في مانا النظام." | |
| # --------- API Models --------- | |
| class HunterStats(BaseModel): | |
| name: str = "صياد" | |
| level: int = 1 | |
| weight: float = 70.0 | |
| height: float = 175.0 | |
| age: int = 20 | |
| targetGoal: str = "الارتقاء" | |
| rank: str = "E-Rank" | |
| customPersona: str = "" | |
| class ChatRequest(BaseModel): | |
| hunter_stats: HunterStats | |
| message: str | |
| class SyncRequest(BaseModel): | |
| hunter_id: str | |
| gold: int | |
| level: int | |
| exp: int | |
| # --------- Routes --------- | |
| def register_user(request: dict): | |
| username = request.get("username", "").strip().lower() | |
| password = request.get("password", "") | |
| if not username or not password: return JSONResponse(status_code=400, content={"error": "Missing data."}) | |
| conn = sqlite3.connect(DB_PATH) | |
| cursor = conn.cursor() | |
| try: | |
| cursor.execute("INSERT INTO users (username, password) VALUES (?, ?)", (username, hash_password(password))) | |
| conn.commit() | |
| return {"message": "تم التسجيل بنجاح."} | |
| except sqlite3.IntegrityError: return JSONResponse(status_code=400, content={"error": "الاسم مستخدم مسبقاً."}) | |
| finally: conn.close() | |
| def login_user(request: dict): | |
| username = request.get("username", "").strip().lower() | |
| password = request.get("password", "") | |
| conn = sqlite3.connect(DB_PATH) | |
| cursor = conn.cursor() | |
| cursor.execute("SELECT password FROM users WHERE username = ?", (username,)) | |
| row = cursor.fetchone() | |
| conn.close() | |
| if row and row[0] == hash_password(password): return {"message": "دخول ناجح.", "username": username} | |
| return JSONResponse(status_code=401, content={"error": "بيانات خاطئة."}) | |
| def sync_progress(request: SyncRequest): | |
| conn = sqlite3.connect(DB_PATH) | |
| cursor = conn.cursor() | |
| try: | |
| cursor.execute('''INSERT INTO progress (hunter_id, gold, level, exp, last_sync) | |
| VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP) | |
| ON CONFLICT(hunter_id) DO UPDATE SET | |
| gold=excluded.gold, level=excluded.level, exp=excluded.exp, last_sync=CURRENT_TIMESTAMP''', | |
| (request.hunter_id, request.gold, request.level, request.exp)) | |
| conn.commit() | |
| return {"status": "success"} | |
| except Exception as e: return JSONResponse(status_code=500, content={"error": str(e)}) | |
| finally: conn.close() | |
| def get_progress(hunter_id: str): | |
| conn = sqlite3.connect(DB_PATH) | |
| cursor = conn.cursor() | |
| cursor.execute("SELECT gold, level, exp FROM progress WHERE hunter_id = ?", (hunter_id,)) | |
| row = cursor.fetchone() | |
| conn.close() | |
| if row: return {"gold": row[0], "level": row[1], "exp": row[2]} | |
| return JSONResponse(status_code=404, content={"error": "لا يوجد سجل."}) | |
| def update_auth(request: dict): | |
| old_username = request.get("old_username", "").strip().lower() | |
| new_username = request.get("new_username", "").strip().lower() | |
| new_password = request.get("new_password", "") | |
| password = request.get("password", "") | |
| conn = sqlite3.connect(DB_PATH) | |
| cursor = conn.cursor() | |
| try: | |
| # Verify old credentials | |
| cursor.execute("SELECT password FROM users WHERE username = ?", (old_username,)) | |
| row = cursor.fetchone() | |
| if not row or row[0] != hash_password(password): | |
| return JSONResponse(status_code=401, content={"error": "فشل التحقق من الهوية."}) | |
| # Update logic | |
| target_username = new_username if new_username else old_username | |
| target_password = hash_password(new_password) if new_password else row[0] | |
| if new_username and new_username != old_username: | |
| # Transactional rename in users + progress | |
| cursor.execute("INSERT OR IGNORE INTO users (username, password) SELECT ?, ? WHERE NOT EXISTS (SELECT 1 FROM users WHERE username = ?)", (new_username, target_password, new_username)) | |
| if cursor.rowcount == 0: return JSONResponse(status_code=400, content={"error": "الاسم الجديد مشغول."}) | |
| cursor.execute("UPDATE progress SET hunter_id = ? WHERE hunter_id = ?", (new_username, old_username)) | |
| cursor.execute("DELETE FROM users WHERE username = ?", (old_username,)) | |
| else: | |
| cursor.execute("UPDATE users SET password = ? WHERE username = ?", (target_password, old_username)) | |
| conn.commit() | |
| return {"message": "تم التحديث بنجاح.", "username": target_username} | |
| except Exception as e: | |
| return JSONResponse(status_code=500, content={"error": str(e)}) | |
| finally: conn.close() | |
| def shadow_chat(request: ChatRequest): | |
| stats = request.hunter_stats | |
| base_prompt = get_system_prompt(stats.customPersona) | |
| context = f"{base_prompt}\n[تحليل الصياد]: الاسم={stats.name}, الرتبة={stats.rank}, م={stats.level}, الهدف={stats.targetGoal}" | |
| reply = query_ai(request.message, system_prompt=context, hunter_id=stats.name) | |
| return {"reply": reply} | |
| # --------- Premium Web UI --------- | |
| HTML_TEMPLATE = """ | |
| <!DOCTYPE html> | |
| <html lang="ar" dir="rtl"> | |
| <head> | |
| <meta charset="UTF-8"><title>ARISE - Shadow Server Console</title> | |
| <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;700&display=swap" rel="stylesheet"> | |
| <style> | |
| body { background: #07070c; color: #fff; font-family: 'Cairo', sans-serif; margin: 0; display: flex; justify-content: center; align-items: center; min-height: 100vh; } | |
| .glass-panel { background: rgba(20, 20, 30, 0.8); backdrop-filter: blur(15px); border: 1px solid rgba(160, 32, 240, 0.3); border-radius: 20px; width: 90%; max-width: 900px; padding: 40px; box-shadow: 0 15px 35px rgba(0,0,0,0.5); } | |
| h1 { color: #a020f0; text-shadow: 0 0 15px #a020f0; text-align: center; font-size: 2.5rem; margin-bottom: 30px; letter-spacing: 2px; } | |
| .server-status { display: flex; align-items: center; justify-content: center; gap: 12px; margin-bottom: 40px; font-weight: bold; color: #00ff00; } | |
| .status-pulse { width: 12px; height: 12px; background: #00ff00; border-radius: 50%; animation: pulse 1.5s infinite; } | |
| @keyframes pulse { 0% { transform: scale(1); opacity: 1; } 50% { transform: scale(1.5); opacity: 0.5; } 100% { transform: scale(1); opacity: 1; } } | |
| .chat-container { height: 400px; overflow-y: auto; background: rgba(0,0,0,0.4); border-radius: 12px; padding: 20px; border: 1px solid #333; margin-bottom: 20px; } | |
| .msg { margin-bottom: 15px; padding: 12px 18px; border-radius: 10px; max-width: 80%; line-height: 1.6; position: relative; } | |
| .bot { background: #1a0a25; border-right: 4px solid #a020f0; margin-right: auto; } | |
| .user { background: #0a0a1a; border-left: 4px solid #007bff; margin-left: auto; text-align: left; } | |
| .input-box { display: flex; gap: 15px; } | |
| input { flex: 1; background: #000; border: 1px solid #444; color: #fff; padding: 15px; border-radius: 10px; font-size: 1rem; outline: none; } | |
| button { background: #a020f0; border: none; color: #fff; padding: 0 25px; border-radius: 10px; cursor: pointer; font-weight: bold; transition: 0.3s; } | |
| button:hover { background: #bf40ff; transform: translateY(-2px); } | |
| </style> | |
| </head> | |
| <body> | |
| <div class="glass-panel"> | |
| <h1>ARISE SHADOW SERVER</h1> | |
| <div class="server-status"><div class="status-pulse"></div> نظام الترقية متصل (SQL ACTIVE)</div> | |
| <div class="chat-container" id="chat"> | |
| <div class="msg bot"><b>[النظام إغريس]:</b> مرحبا بك أيها الصياد في وحدة التحكم السحابية. أخبرني بمطلبك.</div> | |
| </div> | |
| <div class="input-box"> | |
| <input type="text" id="input" placeholder="اكتب رسالتك لمرشد الظلال..." onkeypress="if(event.key==='Enter') send()"> | |
| <button onclick="send()">إرسال</button> | |
| </div> | |
| </div> | |
| <script> | |
| async function send() { | |
| const input = document.getElementById('input'); | |
| const chat = document.getElementById('chat'); | |
| const val = input.value.trim(); if(!val) return; | |
| input.value = ''; | |
| chat.innerHTML += `<div class="msg user"><b>أنت:</b> ${val}</div>`; | |
| chat.scrollTop = chat.scrollHeight; | |
| try { | |
| const res = await fetch('/chat', { | |
| method: 'POST', | |
| headers: {'Content-Type': 'application/json', 'X-Shadow-Key': 'SHADOW_MONARCH_SECRET_2026'}, | |
| body: JSON.stringify({hunter_stats: {name: 'Admin', level: 99}, message: val}) | |
| }); | |
| const data = await res.json(); | |
| chat.innerHTML += `<div class="msg bot"><b>[النظام إغريس]:</b> ${data.reply}</div>`; | |
| chat.scrollTop = chat.scrollHeight; | |
| } catch(e) { chat.innerHTML += `<div class="msg bot" style="color:red">فشل الاتصال بعالم الظلال!</div>`; } | |
| } | |
| </script> | |
| </body> | |
| </html> | |
| """ | |
| def serve_ui(): | |
| return HTML_TEMPLATE | |