Update app.py
Browse files11 unmodified lines121314151617181920212223248 unmodified lines333435363738392 unmodified lines42434445464713 unmodified lines616263646566676818 unmodified lines878889909192939495969798991001011021031041051061071081091101118 unmodified lines12012112212312412512612 unmodified lines13914014114214314414515 unmodified lines1611621631641651661673 unmodified lines1711721731741751761771781791809 unmodified lines1901911921931941951961971981992002012022032042052062072082092102112122132142152162172182 unmodified lines2212222232242252262272282292302312322332342352362372382392402412422439 unmodified lines2532542552562572582592602612622632642653 unmodified lines2692702712722732742752765 unmodified lines2822832842852862872882892902912922932942954 unmodified lines3003013023033043053063073083093103113123133146 unmodified lines32132232332432532632710 unmodified lines3383393403413423433446 unmodified lines3513523533543553563573581 unmodified line36036136236336436536636720 unmodified lines3883893903913923933941 unmodified line3963973983994004014023 unmodified lines4064074084094104114125 unmodified lines41841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246315 unmodified lines4794804814824834844854 unmodified lines49049149249349449549649742 unmodified lines54054154254354454554654754826 unmodified lines57557657757857958058158258358414 unmodified lines5996006016026036046056066076086096 unmodified lines6166176186196206216221 unmodified line6246256266276286296306316326336346356366376386396406417 unmodified lines6496506516526536546556566576586596606616626636646656666676686696706716726736746756766772 unmodified lines6806816826836846856866876886896906916926 unmodified lines6997007017027037047057067077087097103 unmodified lines7147157167177187197207217227237247251 unmodified line7277287297307317327337347357367377 unmodified lines74574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782811 unmodified lines# ==========================================# 1. SİSTEM VƏ LOGİNG QURAŞDIRILMASI# ==========================================# Terminalda xətaları daha detallı görmək üçün logging sistemilogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')logger = logging.getLogger(__name__)app = Flask(__name__)# Tokenlərin yoxlanılması və yüklənməsiHF_TOKEN = os.getenv("HF_TOKEN")GROQ_API_KEY = os.getenv("GROQ_API_KEY")8 unmodified lines# ==========================================# 2. FRONTEND - NƏHƏNG UI/UX ARXİTEKTURASI# ==========================================# Bu HTML bloku daxilində tam müstəqil CSS, JS, Markdown parser və Notification sistemi var.HTML_TEMPLATE = """<!DOCTYPE html><html lang="az">2 unmodified lines<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>Exypos AI | 4-Core Engine</title><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"><style>/* --- KÖKLÜ DƏYİŞƏNLƏR (CSS VARIABLES) --- */:root {13 unmodified lines--transition-speed: 0.4s;}/* --- SIFIRLAMA VƏ ƏSAS QAYDALAR --- */* { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Inter', 'Segoe UI', system-ui, sans-serif; -webkit-tap-highlight-color: transparent; }::-webkit-scrollbar { width: 6px; }::-webkit-scrollbar-track { background: transparent; }::-webkit-scrollbar-thumb { background: #333; border-radius: 10px; }18 unmodified lines@keyframes float1 { 0% { transform: translate(0, 0) scale(1); } 100% { transform: translate(15vw, 20vh) scale(1.2); } }@keyframes float2 { 0% { transform: translate(0, 0) scale(1); } 100% { transform: translate(-20vw, -15vh) scale(1.1); } }/* --- BAŞLANĞIC (SPLASH) EKRANI --- */#splash {position: fixed; inset: 0; background: var(--bg-ultra-dark); z-index: 9999;display: flex; flex-direction: column; justify-content: center; align-items: center;transition: opacity 1s cubic-bezier(0.16, 1, 0.3, 1), visibility 1s;}.splash-text {font-size: 3rem; font-weight: 900; letter-spacing: 0.5rem; color: var(--color-white);opacity: 0; filter: blur(20px); transform: scale(1.1);animation: cinematicReveal 2s cubic-bezier(0.16, 1, 0.3, 1) forwards 0.2s;}.splash-sub {font-size: 0.8rem; letter-spacing: 0.3rem; color: var(--accent-normal); margin-top: 20px;opacity: 0; animation: fadeUp 1s ease forwards 1s; text-transform: uppercase;}@keyframes cinematicReveal { 100% { opacity: 1; filter: blur(0); transform: scale(1); } }@keyframes fadeUp { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }/* --- ÜST PANEL (HEADER) --- */.top-bar {position: fixed; top: 0; left: 0; width: 100%; height: 80px;display: flex; justify-content: space-between; align-items: center;8 unmodified lines}.menu-btn:hover { background: rgba(255,255,255,0.1); transform: scale(1.05); }/* Profil UI (Dairəvi) */.profile-container {pointer-events: auto; display: flex; align-items: center; gap: 15px;background: var(--bg-panel); backdrop-filter: blur(15px);12 unmodified lines.profile-status { font-size: 0.75rem; font-weight: 500; display: flex; align-items: center; gap: 5px; transition: color 0.3s; }.status-dot { width: 8px; height: 8px; border-radius: 50%; transition: background 0.3s; box-shadow: 0 0 8px currentColor; }/* --- YAN PANEL (SIDEBAR) --- */.sidebar {position: fixed; top: 0; left: -350px; width: 320px; height: 100%;background: rgba(5, 5, 5, 0.95); backdrop-filter: blur(20px);15 unmodified linestransition: all 0.2s;}.new-chat-btn:hover { background: #e2e8f0; transform: translateY(-2px); }.new-chat-btn:active { transform: translateY(0); }.history-list { flex: 1; overflow-y: auto; display: flex; flex-direction: column; gap: 8px; }.history-item {3 unmodified lineswhite-space: nowrap; overflow: hidden; text-overflow: ellipsis;}.history-item:hover { background: rgba(255,255,255,0.08); color: var(--color-text-main); }.history-item.active {background: rgba(255,255,255,0.1); color: var(--color-white);border-left: 3px solid var(--accent-normal);}/* --- ƏSAS ÇAT SAHƏSİ --- */.chat-container {9 unmodified lines}.messages-area { flex: 1; overflow-y: auto; padding: 30px; scroll-behavior: smooth; display: flex; flex-direction: column; gap: 25px; }/* Mesaj Dizaynları */.message-row { display: flex; width: 100%; animation: slideInUp 0.4s ease forwards; opacity: 0; transform: translateY(15px); }@keyframes slideInUp { to { opacity: 1; transform: translateY(0); } }.msg-user { justify-content: flex-start; }.msg-bot { justify-content: flex-end; position: relative; padding-right: 55px; }.bubble {max-width: 85%; padding: 14px 20px; font-size: 0.95rem; line-height: 1.6;letter-spacing: 0.2px; border-radius: 18px; position: relative; word-wrap: break-word;}.msg-user .bubble {background: var(--bubble-user); border: 1px solid var(--glass-border);border-left: 3px solid var(--color-text-muted); border-radius: 18px 18px 18px 4px;color: #e2e8f0;}.msg-bot .bubble {background: var(--bubble-bot); border: 1px solid var(--glass-border);border-right: 3px solid var(--color-white); border-radius: 18px 18px 4px 18px;color: var(--color-white); box-shadow: 0 10px 25px rgba(0,0,0,0.3);}/* Bot Dairəvi Avatarı (Mesajın yanında) */.msg-bot::after {content: '\\f544'; font-family: "Font Awesome 6 Free"; font-weight: 900;position: absolute; right: 0; bottom: 0; width: 40px; height: 40px;2 unmodified linesbox-shadow: 0 4px 15px rgba(255,255,255,0.15); border: 2px solid #222;}/* --- KOD BLOKLARI ÜÇÜN XÜSUSİ DİZAYN --- */pre { background: #0f172a; border-radius: 10px; padding: 15px; overflow-x: auto; margin: 10px 0; border: 1px solid #1e293b; }code { font-family: 'Courier New', Courier, monospace; color: #38bdf8; font-size: 0.85rem; }p code { background: rgba(255,255,255,0.1); padding: 2px 6px; border-radius: 4px; color: #f472b6; }.msg-bot img { max-width: 100%; border-radius: 12px; margin-top: 10px; box-shadow: 0 5px 15px rgba(0,0,0,0.4); }/* Yazma effekti kursoru */.typing-cursor::after { content: '▋'; animation: blink 1s step-end infinite; color: var(--accent-normal); margin-left: 5px; }@keyframes blink { 50% { opacity: 0; } }/* --- İNPUT ZONASI VƏ 4 MÜHƏRRİK MENYUSU --- */.input-wrapper {position: fixed; bottom: 30px; left: 50%; transform: translateX(-50%);width: 90%; max-width: 800px; display: flex; flex-direction: column; align-items: center; z-index: 100;}/* 4 Mod menyusu (Açılan) */.engine-selector {position: absolute; bottom: 70px; background: rgba(10,10,10,0.98); backdrop-filter: blur(25px);border: 1px solid #333; border-radius: 20px; padding: 8px; display: flex; flex-direction: column; gap: 4px;9 unmodified lines}.engine-btn:hover { background: rgba(255,255,255,0.05); color: white; }.engine-btn.active { background: rgba(255,255,255,0.1); color: white; }.btn-normal.active { border-left: 3px solid var(--accent-normal); }.btn-thinking.active { border-left: 3px solid var(--accent-thinking); }.btn-plus.active { border-left: 3px solid var(--accent-plus); }.btn-ultra.active { border-left: 3px solid var(--accent-ultra); }/* Əsas Input Paneli */.input-box {width: 100%; display: flex; align-items: center; gap: 10px; background: rgba(20,20,20,0.9);backdrop-filter: blur(20px); border: 1px solid rgba(255,255,255,0.1); border-radius: 50px;3 unmodified lines.engine-toggle-btn {background: rgba(255,255,255,0.05); border: 1px solid transparent; color: var(--color-text-muted);width: 40px; height: 40px; border-radius: 50%; cursor: pointer; display: flex; align-items: center;justify-content: center; transition: 0.3s;}.engine-toggle-btn:hover { background: rgba(255,255,255,0.1); color: white; transform: rotate(90deg); }5 unmodified linestextarea::placeholder { color: #555; }.send-btn {background: var(--color-white); color: #000; border: none; width: 45px; height: 45px;border-radius: 50%; cursor: pointer; display: flex; align-items: center; justify-content: center;font-size: 1.1rem; transition: 0.3s; box-shadow: 0 0 15px rgba(255,255,255,0.2);}.send-btn:hover { transform: scale(1.05); background: #f1f5f9; }.send-btn:disabled { opacity: 0.5; cursor: not-allowed; transform: none; }/* --- BİLDİRİŞLƏR (TOAST NOTIFICATIONS) --- */#toast-container { position: fixed; bottom: 100px; right: 20px; display: flex; flex-direction: column; gap: 10px; z-index: 6000; pointer-events: none; }.toast {background: rgba(20,20,20,0.95); border: 1px solid #333; color: white; padding: 12px 20px;4 unmodified lines@keyframes toastIn { from { opacity: 0; transform: translateX(50px); } to { opacity: 1; transform: translateX(0); } }@keyframes toastOut { to { opacity: 0; transform: translateY(-20px) scale(0.9); } }/* Loader */.typing-indicator { display: flex; gap: 4px; padding: 5px 10px; align-items: center; height: 30px;}.typing-indicator span { width: 6px; height: 6px; background: #888; border-radius: 50%; animation: bounce 1.4s infinite ease-in-out both; }.typing-indicator span:nth-child(1) { animation-delay: -0.32s; }.typing-indicator span:nth-child(2) { animation-delay: -0.16s; }@keyframes bounce { 0%, 80%, 100% { transform: scale(0); } 40% { transform: scale(1); } }/* Responsive */@media (max-width: 768px) {.glass-wrapper { width: 100%; border-radius: 0; border: none; border-top: 1px solid #333; }.input-wrapper { width: 95%; bottom: 15px; }.profile-container { padding: 5px 15px 5px 5px; }6 unmodified lines</head><body><div id="splash"><div class="splash-text">HEX</div><div class="splash-sub">Core Engine Initializing...</div></div>10 unmodified lines<div class="profile-container"><div class="profile-avatar"><i class="fa-solid fa-microchip"></i></div><div class="profile-info"><span class="profile-name">HEX System</span><span class="profile-status" id="status-display"><span class="status-dot" style="background: var(--accent-normal)"></span> Mod: Normal</span>6 unmodified lines<button class="new-chat-btn" onclick="appController.createNewSession()"><i class="fa-solid fa-bolt"></i> YENİ SESSİYA</button><div class="history-list" id="history-container"></div><div style="margin-top: auto; padding-top: 20px; border-top: 1px solid #333; text-align: center;"><span style="font-size: 0.7rem; color: #666; letter-spacing: 2px;">V1.0.0 ENGINE ARCHITECTURE</span></div>1 unmodified line<main class="chat-container"><div class="glass-wrapper"><div class="messages-area" id="chat-messages"></div></div></main>20 unmodified lines</button><textarea id="main-input" rows="1" placeholder="Sistemi işə sal... (/sekil ilə şəkil yarat)" oninput="this.style.height = '';this.style.height = this.scrollHeight + 'px'"></textarea><button class="send-btn" id="send-btn" onclick="appController.handleSend()"><i class="fa-solid fa-arrow-up"></i></button></div></div>1 unmodified line<div id="toast-container"></div><script>// --- UTILS: Tost Bildirişləri ---const Toast = {show: function(msg, type = 'info') {const container = document.getElementById('toast-container');3 unmodified lineslet icon = '<i class="fa-solid fa-circle-info text-blue-400"></i>';if(type === 'success') icon = '<i class="fa-solid fa-circle-check text-green-400"></i>';if(type === 'error') icon = '<i class="fa-solid fa-circle-exclamation text-red-400"></i>';if(type === 'warning') icon = '<i class="fa-solid fa-triangle-exclamation text-orange-400"></i>';toast.innerHTML = `${icon} <span>${msg}</span>`;container.appendChild(toast);5 unmodified lines}};// --- UTILS: Sadə Markdown Parser (Bold və Kod Blokları üçün) ---const MarkdownParser = {parse: function(text) {// Kod blokları: ```kod```let html = text.replace(/```([a-z]*)\n([\s\S]*?)```/g, '<pre><code class="language-$1">$2</code></pre>');// İşıqlı kod parçaları: `kod`html = html.replace(/`([^`]+)`/g, '<code>$1</code>');// Qalın yazılar: **yazı**html = html.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');// Sətir sonlarıhtml = html.replace(/\n/g, '<br>');return html;}};// --- ƏSAS TƏTBİQ KONTROLLERİ ---const appController = {dbName: 'HEX_DB_V1',activeSessionId: null,sessions: {},currentEngine: 'Normal',isGenerating: false,init: function() {// Splash screen gizlətməsetTimeout(() => {const splash = document.getElementById('splash');splash.style.opacity = '0';setTimeout(() => splash.style.display = 'none', 1000);Toast.show('HEX System Online', 'success');}, 1500);// DB Yükləməconst saved = localStorage.getItem(this.dbName);if (saved) {try {this.sessions = JSON.parse(saved);this.activeSessionId = localStorage.getItem(this.dbName + '_ACTIVE');} catch(e) { console.error("DB Error"); }}if (!this.activeSessionId || !this.sessions[this.activeSessionId]) {this.createNewSession();15 unmodified lines}});// Menyudan kənara basanda bağlamaqdocument.addEventListener('click', (e) => {const menu = document.getElementById('engine-selector');const btn = document.getElementById('toggle-engine-btn');4 unmodified lines},saveDB: function() {localStorage.setItem(this.dbName, JSON.stringify(this.sessions));localStorage.setItem(this.dbName + '_ACTIVE', this.activeSessionId);this.renderSidebar();},42 unmodified lines}},toggleEngineMenu: function() {document.getElementById('engine-selector').classList.toggle('show');},setMode: function(mode) {this.currentEngine = mode;26 unmodified linesdiv.className = `message-row msg-${sender}`;const formattedContent = (sender === 'bot' && !isHTML) ? MarkdownParser.parse(content) : content;div.innerHTML = `<div class="bubble">${formattedContent}</div>`;// İlk mesajdırsa köhnə boş ekranı təmizləif (box.children.length === 1 && box.children[0].innerHTML.includes('AWAITING COMMAND')) {box.innerHTML = '';}14 unmodified linesconst div = document.createElement('div');div.className = `message-row msg-bot`;div.id = id;div.innerHTML = `<div class="bubble" style="padding: 10px 15px; color: #888;"><div class="typing-indicator"><span></span><span></span><span></span></div></div>`;box.appendChild(div);box.scrollTop = box.scrollHeight;return id;6 unmodified linesconst text = inputEl.value.trim();if (!text) return;// Başlığın avtomatik yaradılmasıif (this.sessions[this.activeSessionId].messages.length === 0) {this.sessions[this.activeSessionId].title = text.substring(0, 20) + (text.length > 20 ? '...' : '');this.renderSidebar();1 unmodified linethis.appendMessageDOM('user', text, true, false);inputEl.value = '';inputEl.style.height = 'auto'; // hündürlüyü sıfırlathis.isGenerating = true;document.getElementById('send-btn').disabled = true;const isImageReq = text.toLowerCase().startsWith("/sekil");let loaderId = this.showTypingIndicator();try {const reqBody = {message: text,mode: this.currentEngine,history: this.sessions[this.activeSessionId].messages.slice(-6) // Son 6 mesajı göndər};const response = await fetch('/chat', {7 unmodified linesif (data.error) {Toast.show("Server xətası: " + data.error, "error");this.appendMessageDOM('bot', `<span style="color:#ef4444"><i class="fa-solid fa-triangle-exclamation"></i> Bağlantı problemi yarandı.</span>`, false, true);} else if (data.type === 'image_url') {const imgHtml = `<img src="${data.content}" alt="Generated Image" onload="document.getElementById('chat-messages').scrollTop = document.getElementById('chat-messages').scrollHeight;">`;this.appendMessageDOM('bot', imgHtml, true, true);Toast.show("Şəkil uğurla yaradıldı", "success");} else {// Typewriter effekti simulyasiyasıconst botDiv = this.appendMessageDOM('bot', '', false, true);const bubble = botDiv.querySelector('.bubble');bubble.classList.add('typing-cursor');// Sadə və sürətli çap effektilet parsedHtml = MarkdownParser.parse(data.content);bubble.innerHTML = parsedHtml;// Yaddaşa qeydthis.sessions[this.activeSessionId].messages.push({ sender: 'bot', content: data.content, isHTML: false });this.saveDB();bubble.classList.remove('typing-cursor');}} catch (error) {document.getElementById(loaderId).remove();Toast.show("Şəbəkə xətası!", "error");} finally {this.isGenerating = false;2 unmodified lines}};// Qlobal funksiya (HTML-dən çağırmaq üçün)function toggleSidebar() {document.getElementById('sidebar').classList.toggle('open');document.getElementById('sidebar-overlay').classList.toggle('open');}// Tətbiqi işə salappController.init();</script></body>6 unmodified lines@app.route('/')def index():"""Əsas səhifəni (Frontend) qaytarır."""return render_template_string(HTML_TEMPLATE)@app.route('/chat', methods=['POST'])def handle_chat():"""Gələn mesajları qəbul edir, analiz edir və müvafiq modelə yönləndirir."""try:data = request.jsonif not data:3 unmodified linesmode = data.get("mode", "Normal")history = data.get("history", [])logger.info(f"Yeni sorğu alındı. Mod: {mode}")# --- ŞƏKİL YARATMA İSTƏYİ ---if user_msg.lower().startswith(("/sekil", "/image", "/şəkil")):logger.info("Şəkil yaratma mühərriki işə düşdü.")# "/sekil" sözünü mətndən təmizləyirikprompt = re.sub(r"^/(sekil|şəkil|image)\s*", "", user_msg, flags=re.IGNORECASE).strip()if not prompt:1 unmodified lineif client_hf:try:# Daha keyfiyyətli nəticə üçün gizli prompt əlavəsienhanced_prompt = f"Highly detailed, 8k resolution, masterpiece, cinematic lighting: {prompt}"image = client_hf.text_to_image(enhanced_prompt, model="runwayml/stable-diffusion-v1-5")# Şəkli yaddaşda byte formatına çevirib Base64 edirikbuffered = io.BytesIO()image.save(buffered, format="PNG")img_str = base64.b64encode(buffered.getvalue()).decode()7 unmodified linesreturn jsonify({"error": "HuggingFace API Token tapılmadı."}), 500# --- 4 FƏRQLİ MÜHƏRRİK ÜÇÜN ÇOX DETALLI TƏLİMATLAR ---# Bu hissə botun şəxsiyyətini, tonunu və xəta ehtimalını (temperatur) idarə edir.engine_configs = {"Normal": {"temperature": 0.7,"system_prompt": """Sən HEX sisteminin 'Normal' mühərrikisən.Məqsədin: Gündəlik, sürətli və səmimi ünsiyyət qurmaqdır.Tonun: Dostyana, amma hörmətli. Çox uzun uzadı elmi cümlələr qurma, sadə və aydın ol.Qayda: İstifadəçi hansı dildə yazırsa, o dildə cavab ver. Qısa köməkliklər göstər."""},"Thinking": {"temperature": 0.5,"system_prompt": """Sən HEX sisteminin 'Thinking' (Analitik) mühərrikisən.Məqsədin: Tələbələrə, öyrənənlərə addım-addım kömək etməkdir.Tonun: Pedagoji, səbirli və analitik.Qayda: Sualın cavabını birbaşa vermək əvəzinə, məntiqi addımlara böl. "Birinci addım", "İkinci addım" kimi strukturlardan istifadə et. İstifadəçini düşünməyə vadar et."""},"Plus": {"temperature": 0.3,"system_prompt": """Sən HEX sisteminin 'Plus' mühərrikisən. Sən fiziki işlər, sənətkarlıq, mexanika və gündəlik həyat bacarıqları üzrə ekspertsən (Usta).Məqsədin: Dülgərlik, avtomobil təmiri, ev işləri, sürücülük kimi mövzularda dəqiq instruksiyalar verməkdir.ƏN ÖNƏMLİ QAYDA: Həmişə TƏHLÜKƏSİZLİK (Safety) qaydalarını vurğula. Məsələn, taxta kəsərkən eynək taxmağı, elektrik işi görərkən cərəyanı kəsməyi mütləq qeyd et. Təhlükəli, qeyri-qanuni və ya özünə zərər verə biləcək hər hansı bir sorğunu birbaşa rədd et!"""},"Ultra": {"temperature": 0.0, # Sıfır xəta üçün ən aşağı temperatur"system_prompt": """Sən HEX sisteminin ən güclü 'Ultra' mühərrikisən. Sən elm, tibb, fizika, biologiya və ən əsası KODLAMA üzrə mütləq ekspertsən.Məqsədin: Sıfır xəta, maksimum dəqiqlik, akademik və peşəkar səviyyədə hesabat və kod təqdim etməkdir.Qaydalar:1. Heç vaxt emosiya bildirmə, "salam", "necəsən" kimi lazımsız sözlər işlətmə. Birbaşa mətləbə keç.2. Kod yazarkən həmişə Markdown (```dil) formatından istifadə et və kodu qüsursuz, optimallaşdırılmış şəkildə yaz.3. Tibbi və ya hüquqi məsləhət verərkən mütləq "Bu rəsmi tibbi məsləhət deyil, peşəkara müraciət edin" xəbərdarlığını sonda qeyd et.4. Məlumatı bullet pointlərlə (siyahı şəklində) qısa və kəskin formatla."""}}# Seçilmiş mühərrikin konfiqurasiyasını çəkirikcurrent_config = engine_configs.get(mode, engine_configs["Normal"])# Mesajların yığılması (Context window yaradılması)messages_to_send = [{"role": "system", "content": current_config["system_prompt"]}]# Tarixçəni (History) əlavə edirik (qısa yaddaş üçün)for msg in history:if not msg.get('isHTML'): # Təmiz mətnləri yaddaşa veririkrole = "user" if msg['sender'] == 'user' else "assistant"messages_to_send.append({"role": role, "content": msg['content']})# Ən son gələn mesajı əlavə edirikmessages_to_send.append({"role": "user", "content": user_msg})# --- GROQ API ÇAĞIRIŞI ---if client_groq:logger.info(f"Groq API çağırılır... (Model: llama-3.3-70b, Temp: {current_config['temperature']})")# API İstəyicompletion = client_groq.chat.completions.create(model="llama-3.3-70b-versatile",messages=messages_to_send,temperature=current_config["temperature"],max_tokens=3000, # Ultra mod üçün uzun cavablar lazım ola bilərtop_p=0.9)response_text = completion.choices[0].message.contentreturn jsonify({"type": "text", "content": response_text})else:logger.error("Groq API açarı konfiqurasiya edilməyib.")return jsonify({"error": "Sistemdə AI mühərriki (Groq) aktiv deyil. API Key yoxlayın."}), 500except Exception as e:logger.error(f"Sistem daxili xəta: {str(e)}", exc_info=True)return jsonify({"error": "Sistem xətası baş verdi. Logs-a baxın."}), 500# ==========================================# 4. SERVERİN BAŞLADILMASI# ==========================================if __name__ == "__main__":logger.info("HEX 4-Core Engine işə düşür...")# debug=True development prosesində səhvləri görmək üçün faydalıdırapp.run(host="0.0.0.0", port=7860, debug=False)11 unmodified lines12131415161718192021228 unmodified lines3132333435362 unmodified lines3940414243444513 unmodified lines5960616263646518 unmodified lines848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191208 unmodified lines12913013113213313412 unmodified lines14714814915015115215315 unmodified lines1691701711721731743 unmodified lines1781791801811821831849 unmodified lines1941951961971981992002012022032042052062072082092 unmodified lines2122132142152162172182192202212222232242252262272282292302319 unmodified lines2412422432442452462472482492502513 unmodified lines2552562572582592602612622635 unmodified lines2692702712722732742752762772782792802812822832844 unmodified lines2892902912922932942952962972982993003013026 unmodified lines30931031131231331431510 unmodified lines3263273283293303313326 unmodified lines3393403413423433443451 unmodified line34734834935035135235320 unmodified lines3743753763773783793801 unmodified line3823833843853863873883 unmodified lines3923933943953963975 unmodified lines40340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444515 unmodified lines4614624634644654664 unmodified lines47147247347447547647747847948042 unmodified lines52352452552652752852926 unmodified lines55655755855956056156256314 unmodified lines5785795805815825835846 unmodified lines5915925935945955961 unmodified line5985996006016026036046056066076086096106116126136147 unmodified lines6226236246256266276286296306316326336346356366376386396406416426432 unmodified lines6466476486496506516526536546556566576 unmodified lines6646656666676686696706716726733 unmodified lines6776786796806816826836841 unmodified line6866876886896906916926936947 unmodified lines70270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275311 unmodified lines# ==========================================# 1. SİSTEM VƏ LOGİNG QURAŞDIRILMASI# ==========================================logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')logger = logging.getLogger(__name__)app = Flask(__name__)HF_TOKEN = os.getenv("HF_TOKEN")GROQ_API_KEY = os.getenv("GROQ_API_KEY")8 unmodified lines# ==========================================# 2. FRONTEND - NƏHƏNG UI/UX ARXİTEKTURASI# ==========================================HTML_TEMPLATE = """<!DOCTYPE html><html lang="az">2 unmodified lines<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>Exypos AI | 4-Core Engine</title><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"><link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300;700;900&family=Inter:wght@400;500;600&display=swap" rel="stylesheet"><style>/* --- KÖKLÜ DƏYİŞƏNLƏR (CSS VARIABLES) --- */:root {13 unmodified lines--transition-speed: 0.4s;}* { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Inter', sans-serif; -webkit-tap-highlight-color: transparent; }::-webkit-scrollbar { width: 6px; }::-webkit-scrollbar-track { background: transparent; }::-webkit-scrollbar-thumb { background: #333; border-radius: 10px; }18 unmodified lines@keyframes float1 { 0% { transform: translate(0, 0) scale(1); } 100% { transform: translate(15vw, 20vh) scale(1.2); } }@keyframes float2 { 0% { transform: translate(0, 0) scale(1); } 100% { transform: translate(-20vw, -15vh) scale(1.1); } }/* --- BAŞLANĞIC (SPLASH) EKRANI (BLUR VƏ NEON EFFEKT) --- */#splash {position: fixed; inset: 0; background: var(--bg-ultra-dark); z-index: 9999;display: flex; flex-direction: column; justify-content: center; align-items: center;transition: opacity 1s cubic-bezier(0.16, 1, 0.3, 1), visibility 1s;}.splash-text {font-family: 'Montserrat', sans-serif;font-size: 4rem;font-weight: 900;letter-spacing: 0.8rem;color: var(--color-white);/* Gözəlləşdirilmiş Blur və Parlama (Neon) Effekti */text-shadow: 0 0 10px rgba(255,255,255,0.8),0 0 30px var(--accent-normal),0 0 60px var(--accent-thinking),0 0 100px var(--accent-normal);opacity: 0; filter: blur(30px); transform: scale(1.2);animation: cinematicReveal 2.5s cubic-bezier(0.16, 1, 0.3, 1) forwards 0.2s;text-align: center;}.splash-sub {font-family: 'Montserrat', sans-serif;font-size: 0.9rem; letter-spacing: 0.4rem; color: var(--color-white); margin-top: 25px;opacity: 0; animation: fadeUp 1.5s ease forwards 1s; text-transform: uppercase;text-shadow: 0 0 10px rgba(255,255,255,0.3);}@keyframes cinematicReveal { 100% { opacity: 1; filter: blur(0); transform: scale(1); } }@keyframes fadeUp { from { opacity: 0; transform: translateY(15px); } to { opacity: 0.8; transform: translateY(0); } }/* --- ÜST PANEL --- */.top-bar {position: fixed; top: 0; left: 0; width: 100%; height: 80px;display: flex; justify-content: space-between; align-items: center;8 unmodified lines}.menu-btn:hover { background: rgba(255,255,255,0.1); transform: scale(1.05); }.profile-container {pointer-events: auto; display: flex; align-items: center; gap: 15px;background: var(--bg-panel); backdrop-filter: blur(15px);12 unmodified lines.profile-status { font-size: 0.75rem; font-weight: 500; display: flex; align-items: center; gap: 5px; transition: color 0.3s; }.status-dot { width: 8px; height: 8px; border-radius: 50%; transition: background 0.3s; box-shadow: 0 0 8px currentColor; }/* --- YAN PANEL --- */.sidebar {position: fixed; top: 0; left: -350px; width: 320px; height: 100%;background: rgba(5, 5, 5, 0.95); backdrop-filter: blur(20px);15 unmodified linestransition: all 0.2s;}.new-chat-btn:hover { background: #e2e8f0; transform: translateY(-2px); }.history-list { flex: 1; overflow-y: auto; display: flex; flex-direction: column; gap: 8px; }.history-item {3 unmodified lineswhite-space: nowrap; overflow: hidden; text-overflow: ellipsis;}.history-item:hover { background: rgba(255,255,255,0.08); color: var(--color-text-main); }.history-item.active { background: rgba(255,255,255,0.1); color: var(--color-white); border-left: 3px solid var(--accent-normal); }/* --- ƏSAS ÇAT SAHƏSİ --- */.chat-container {9 unmodified lines}.messages-area { flex: 1; overflow-y: auto; padding: 30px; scroll-behavior: smooth; display: flex; flex-direction: column; gap: 25px; }.message-row { display: flex; width: 100%; animation: slideInUp 0.4s ease forwards; opacity: 0; transform: translateY(15px); }@keyframes slideInUp { to { opacity: 1; transform: translateY(0); } }.msg-user { justify-content: flex-start; }.msg-bot { justify-content: flex-end; position: relative; padding-right: 55px; }.bubble { max-width: 85%; padding: 14px 20px; font-size: 0.95rem; line-height: 1.6; border-radius: 18px; position: relative; word-wrap: break-word; }.msg-user .bubble { background: var(--bubble-user); border: 1px solid var(--glass-border); border-left: 3px solid var(--color-text-muted); border-radius: 18px 18px 18px 4px; color: #e2e8f0; }.msg-bot .bubble { background: var(--bubble-bot); border: 1px solid var(--glass-border); border-right: 3px solid var(--color-white); border-radius: 18px 18px 4px 18px; color: var(--color-white); box-shadow: 0 10px 25px rgba(0,0,0,0.3); }.msg-bot::after {content: '\\f544'; font-family: "Font Awesome 6 Free"; font-weight: 900;position: absolute; right: 0; bottom: 0; width: 40px; height: 40px;2 unmodified linesbox-shadow: 0 4px 15px rgba(255,255,255,0.15); border: 2px solid #222;}pre { background: #0f172a; border-radius: 10px; padding: 15px; overflow-x: auto; margin: 10px 0; border: 1px solid #1e293b; }code { font-family: 'Courier New', Courier, monospace; color: #38bdf8; font-size: 0.85rem; }p code { background: rgba(255,255,255,0.1); padding: 2px 6px; border-radius: 4px; color: #f472b6; }.msg-bot img { max-width: 100%; border-radius: 12px; margin-top: 10px; box-shadow: 0 5px 15px rgba(0,0,0,0.4); }.typing-cursor::after { content: '▋'; animation: blink 1s step-end infinite; color: var(--accent-normal); margin-left: 5px; }@keyframes blink { 50% { opacity: 0; } }/* --- İNPUT ZONASI --- */.input-wrapper {position: fixed; bottom: 30px; left: 50%; transform: translateX(-50%);width: 90%; max-width: 800px; display: flex; flex-direction: column; align-items: center; z-index: 100;}.engine-selector {position: absolute; bottom: 70px; background: rgba(10,10,10,0.98); backdrop-filter: blur(25px);border: 1px solid #333; border-radius: 20px; padding: 8px; display: flex; flex-direction: column; gap: 4px;9 unmodified lines}.engine-btn:hover { background: rgba(255,255,255,0.05); color: white; }.engine-btn.active { background: rgba(255,255,255,0.1); color: white; }.btn-normal.active { border-left: 3px solid var(--accent-normal); }.btn-thinking.active { border-left: 3px solid var(--accent-thinking); }.btn-plus.active { border-left: 3px solid var(--accent-plus); }.btn-ultra.active { border-left: 3px solid var(--accent-ultra); }.input-box {width: 100%; display: flex; align-items: center; gap: 10px; background: rgba(20,20,20,0.9);backdrop-filter: blur(20px); border: 1px solid rgba(255,255,255,0.1); border-radius: 50px;3 unmodified lines.engine-toggle-btn {background: rgba(255,255,255,0.05); border: 1px solid transparent; color: var(--color-text-muted);border-radius: 50%; cursor: pointer; display: flex; align-items: center; justify-content: center; transition: 0.3s;/* Əzilmənin qarşısını alan qızıl kodlar */flex-shrink: 0; min-width: 40px; min-height: 40px;}.engine-toggle-btn:hover { background: rgba(255,255,255,0.1); color: white; transform: rotate(90deg); }5 unmodified linestextarea::placeholder { color: #555; }.send-btn {background: var(--color-white); color: #000; border: none;border-radius: 50%; cursor: pointer; display: flex; align-items: center; justify-content: center;font-size: 1.1rem; transition: 0.3s; box-shadow: 0 0 15px rgba(255,255,255,0.2);/* Düymənin əzilməsini ləğv etmək üçün! */flex-shrink: 0; min-width: 45px; min-height: 45px;}.send-btn:hover { transform: scale(1.05); background: #f1f5f9; }.send-btn:disabled { opacity: 0.5; cursor: not-allowed; transform: none; }/* --- BİLDİRİŞLƏR --- */#toast-container { position: fixed; bottom: 100px; right: 20px; display: flex; flex-direction: column; gap: 10px; z-index: 6000; pointer-events: none; }.toast {background: rgba(20,20,20,0.95); border: 1px solid #333; color: white; padding: 12px 20px;4 unmodified lines@keyframes toastIn { from { opacity: 0; transform: translateX(50px); } to { opacity: 1; transform: translateX(0); } }@keyframes toastOut { to { opacity: 0; transform: translateY(-20px) scale(0.9); } }.typing-indicator { display: flex; gap: 4px; padding: 5px 10px; align-items: center; height: 30px;}.typing-indicator span { width: 6px; height: 6px; background: #888; border-radius: 50%; animation: bounce 1.4s infinite ease-in-out both; }.typing-indicator span:nth-child(1) { animation-delay: -0.32s; }.typing-indicator span:nth-child(2) { animation-delay: -0.16s; }@keyframes bounce { 0%, 80%, 100% { transform: scale(0); } 40% { transform: scale(1); } }@media (max-width: 768px) {.splash-text { font-size: 2.8rem; }.glass-wrapper { width: 100%; border-radius: 0; border: none; border-top: 1px solid #333; }.input-wrapper { width: 95%; bottom: 15px; }.profile-container { padding: 5px 15px 5px 5px; }6 unmodified lines</head><body><div id="splash"><div class="splash-text">EXYPOS AI</div><div class="splash-sub">Core Engine Initializing...</div></div>10 unmodified lines<div class="profile-container"><div class="profile-avatar"><i class="fa-solid fa-microchip"></i></div><div class="profile-info"><span class="profile-name">Exypos AI</span><span class="profile-status" id="status-display"><span class="status-dot" style="background: var(--accent-normal)"></span> Mod: Normal</span>6 unmodified lines<button class="new-chat-btn" onclick="appController.createNewSession()"><i class="fa-solid fa-bolt"></i> YENİ SESSİYA</button><div class="history-list" id="history-container"></div><div style="margin-top: auto; padding-top: 20px; border-top: 1px solid #333; text-align: center;"><span style="font-size: 0.7rem; color: #666; letter-spacing: 2px;">V1.0.0 ENGINE ARCHITECTURE</span></div>1 unmodified line<main class="chat-container"><div class="glass-wrapper"><div class="messages-area" id="chat-messages"></div></div></main>20 unmodified lines</button><textarea id="main-input" rows="1" placeholder="Sistemi işə sal... (/sekil ilə şəkil yarat)" oninput="this.style.height = '';this.style.height = this.scrollHeight + 'px'"></textarea><button class="send-btn" id="send-btn" onclick="appController.handleSend()"><i class="fa-solid fa-paper-plane"></i></button></div></div>1 unmodified line<div id="toast-container"></div><script>// Üzərindəki donma problemini həll etmək üçün LocalStorage xətaları tutulur.const Toast = {show: function(msg, type = 'info') {const container = document.getElementById('toast-container');3 unmodified lineslet icon = '<i class="fa-solid fa-circle-info text-blue-400"></i>';if(type === 'success') icon = '<i class="fa-solid fa-circle-check text-green-400"></i>';if(type === 'error') icon = '<i class="fa-solid fa-circle-exclamation text-red-400"></i>';toast.innerHTML = `${icon} <span>${msg}</span>`;container.appendChild(toast);5 unmodified lines}};const MarkdownParser = {parse: function(text) {let html = text.replace(/```([a-z]*)\n([\s\S]*?)```/g, '<pre><code class="language-$1">$2</code></pre>');html = html.replace(/`([^`]+)`/g, '<code>$1</code>');html = html.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');html = html.replace(/\n/g, '<br>');return html;}};const appController = {dbName: 'EXYPOS_ULTRA_V3', // DB adını dəyişdik ki, köhnə problemli data ilə qarışmasın!activeSessionId: null,sessions: {},currentEngine: 'Normal',isGenerating: false,init: function() {// Splash ekranı qəşəng və etibarlı şəkildə bağlayırıqsetTimeout(() => {const splash = document.getElementById('splash');splash.style.opacity = '0';setTimeout(() => { splash.style.display = 'none'; }, 1000);Toast.show('Exypos AI Aktivdir', 'success');}, 2500); // Parlaq effektin görünməsi üçün bir az daha uzun// Güvənli LocalStorage Yükləməsitry {const saved = localStorage.getItem(this.dbName);if (saved) {const parsed = JSON.parse(saved);if(parsed && typeof parsed === 'object') {this.sessions = parsed;this.activeSessionId = localStorage.getItem(this.dbName + '_ACTIVE');}}} catch(e) { console.error("DB Yüklənmə Xətası, yeni DB yaradılır."); this.sessions = {}; }if (!this.activeSessionId || !this.sessions[this.activeSessionId]) {this.createNewSession();15 unmodified lines}});document.addEventListener('click', (e) => {const menu = document.getElementById('engine-selector');const btn = document.getElementById('toggle-engine-btn');4 unmodified lines},saveDB: function() {try {localStorage.setItem(this.dbName, JSON.stringify(this.sessions));localStorage.setItem(this.dbName + '_ACTIVE', this.activeSessionId);} catch(e) { console.error("Save Error"); }this.renderSidebar();},42 unmodified lines}},toggleEngineMenu: function() { document.getElementById('engine-selector').classList.toggle('show'); },setMode: function(mode) {this.currentEngine = mode;26 unmodified linesdiv.className = `message-row msg-${sender}`;const formattedContent = (sender === 'bot' && !isHTML) ? MarkdownParser.parse(content) : content;div.innerHTML = `<div class="bubble">${formattedContent}</div>`;if (box.children.length === 1 && box.children[0].innerHTML.includes('AWAITING COMMAND')) {box.innerHTML = '';}14 unmodified linesconst div = document.createElement('div');div.className = `message-row msg-bot`;div.id = id;div.innerHTML = `<div class="bubble" style="padding: 10px 15px; color: #888;"><div class="typing-indicator"><span></span><span></span><span></span></div></div>`;box.appendChild(div);box.scrollTop = box.scrollHeight;return id;6 unmodified linesconst text = inputEl.value.trim();if (!text) return;if (this.sessions[this.activeSessionId].messages.length === 0) {this.sessions[this.activeSessionId].title = text.substring(0, 20) + (text.length > 20 ? '...' : '');this.renderSidebar();1 unmodified linethis.appendMessageDOM('user', text, true, false);inputEl.value = '';inputEl.style.height = 'auto';this.isGenerating = true;document.getElementById('send-btn').disabled = true;let loaderId = this.showTypingIndicator();try {const reqBody = {message: text,mode: this.currentEngine,history: this.sessions[this.activeSessionId].messages.slice(-6)};const response = await fetch('/chat', {7 unmodified linesif (data.error) {Toast.show("Server xətası: " + data.error, "error");this.appendMessageDOM('bot', `<span style="color:#ef4444">Bağlantı problemi yarandı.</span>`, false, true);} else if (data.type === 'image_url') {const imgHtml = `<img src="${data.content}" alt="Generated Image" onload="document.getElementById('chat-messages').scrollTop = document.getElementById('chat-messages').scrollHeight;">`;this.appendMessageDOM('bot', imgHtml, true, true);Toast.show("Şəkil yaradıldı", "success");} else {const botDiv = this.appendMessageDOM('bot', '', false, true);const bubble = botDiv.querySelector('.bubble');bubble.innerHTML = MarkdownParser.parse(data.content);this.sessions[this.activeSessionId].messages.push({ sender: 'bot', content: data.content, isHTML: false });this.saveDB();}} catch (error) {if(document.getElementById(loaderId)) document.getElementById(loaderId).remove();Toast.show("Şəbəkə xətası!", "error");} finally {this.isGenerating = false;2 unmodified lines}};function toggleSidebar() {document.getElementById('sidebar').classList.toggle('open');document.getElementById('sidebar-overlay').classList.toggle('open');}// JS BaşlanğıcıappController.init();</script></body>6 unmodified lines@app.route('/')def index():return render_template_string(HTML_TEMPLATE)@app.route('/chat', methods=['POST'])def handle_chat():try:data = request.jsonif not data:3 unmodified linesmode = data.get("mode", "Normal")history = data.get("history", [])# --- ŞƏKİL YARATMA ---if user_msg.lower().startswith(("/sekil", "/image", "/şəkil")):prompt = re.sub(r"^/(sekil|şəkil|image)\s*", "", user_msg, flags=re.IGNORECASE).strip()if not prompt:1 unmodified lineif client_hf:try:enhanced_prompt = f"Highly detailed, 8k resolution, masterpiece, cinematic lighting: {prompt}"image = client_hf.text_to_image(enhanced_prompt, model="runwayml/stable-diffusion-v1-5")buffered = io.BytesIO()image.save(buffered, format="PNG")img_str = base64.b64encode(buffered.getvalue()).decode()7 unmodified linesreturn jsonify({"error": "HuggingFace API Token tapılmadı."}), 500# --- 4 FƏRQLİ MÜHƏRRİK ---engine_configs = {"Normal": {"temperature": 0.7,"system_prompt": "Sən Exypos AI-ın 'Normal' mühərrikisən. Məqsədin gündəlik, sürətli və səmimi ünsiyyət qurmaqdır. İnsan kimi və aydın danış."},"Thinking": {"temperature": 0.5,"system_prompt": "Sən 'Thinking' (Analitik) mühərriksən. Tələbələrə öyrətmək üçün mövzuları addım-addım parçala və məntiqlə izah et."},"Plus": {"temperature": 0.3,"system_prompt": "Sən 'Plus' mühərrikisən. Fiziki işlər, maşın təmiri, sənətkarlıq üzrə ustasan. ƏN ÖNƏMLİSİ: Həmişə təhlükəsizlik (Safety) qaydalarını vurğula."},"Ultra": {"temperature": 0.0,"system_prompt": "Sən 'Ultra' mühərriksən. Kodlama, elm və cərrahi məlumatlar üzrə sıfır xəta ilə işləyirsən. Çox dəqiq, akademik ol və kodları mütləq Markdown formatında yaz."}}current_config = engine_configs.get(mode, engine_configs["Normal"])messages_to_send = [{"role": "system", "content": current_config["system_prompt"]}]for msg in history:if not msg.get('isHTML'):role = "user" if msg['sender'] == 'user' else "assistant"messages_to_send.append({"role": role, "content": msg['content']})messages_to_send.append({"role": "user", "content": user_msg})# --- GROQ API ÇAĞIRIŞI ---if client_groq:completion = client_groq.chat.completions.create(model="llama-3.3-70b-versatile",messages=messages_to_send,temperature=current_config["temperature"],max_tokens=3000,top_p=0.9)response_text = completion.choices[0].message.contentreturn jsonify({"type": "text", "content": response_text})else:return jsonify({"error": "Sistemdə AI mühərriki (Groq) aktiv deyil. API Key yoxlayın."}), 500except Exception as e:logger.error(f"Sistem daxili xəta: {str(e)}", exc_info=True)return jsonify({"error": "Sistem xətası baş verdi. Logs-a baxın."}), 500if __name__ == "__main__":app.run(host="0.0.0.0", port=7860, debug=False)
app.py+81-156