appimg / a.html
Hosdroid's picture
Update a.html
92b7afd verified
Raw History Blame Contribute Delete
17.1 kB
+++ index.html (修改后)
<!DOCTYPE html><html lang="fa" dir="rtl"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>ابرهوش کوکب</title><script src="https://cdn.tailwindcss.com"></script><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"><script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script><script>tailwind.config={theme:{extend:{colors:{kokab:{900:"#0f172a",800:"#1e293b",700:"#334155"}},fontFamily:{sans:["Vazirmatn","Tahoma"]}}}}</script><style>@import url("https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700&display=swap");*{box-sizing:border-box;margin:0;padding:0}body{font-family:"Vazirmatn",sans-serif;background:linear-gradient(135deg,#0f172a 0%,#1e293b 50%,#0f172a 100%);color:#e2e8f0;overflow-x:hidden;min-height:100vh}#particle-canvas{position:fixed;top:0;left:0;width:100%;height:100%;z-index:0;pointer-events:none}.message-enter{animation:messageEnter .3s ease-out}@keyframes messageEnter{from{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}.typing-dot{animation:typingDot 1.4s infinite ease-in-out both}.typing-dot:nth-child(1){animation-delay:-.32s}.typing-dot:nth-child(2){animation-delay:-.16s}@keyframes typingDot{0%,80%,100%{transform:scale(0)}40%{transform:scale(1)}}.glass{background:rgba(30,41,59,.7);backdrop-filter:blur(10px);border:1px solid rgba(255,255,255,.1)}.markdown-body{line-height:1.8}.markdown-body pre{background:#0f172a;padding:1rem;border-radius:8px;overflow-x:auto}.markdown-body code{background:#334155;padding:.2rem .4rem;border-radius:4px;font-family:monospace}.markdown-body pre code{background:0 0;padding:0}.modal-enter{animation:modalEnter .3s ease-out}@keyframes modalEnter{from{opacity:0;transform:scale(.9)}to{opacity:1;transform:scale(1)}}.sidebar{transition:transform .3s}@media(max-width: 768px){.sidebar-hidden{transform:translateX(100%)}}</style></head><body><canvas id="particle-canvas"></canvas>
// ==================== AGENT 1: UI/UX Architect ====================
const UIAgent={particles:[],canvas:null,ctx:null,init(){this.initParticles();this.animateParticles();this.loadSettings();this.renderTools();},initParticles(){this.canvas=document.getElementById('particle-canvas');this.ctx=this.canvas.getContext('2d');this.resizeCanvas();window.addEventListener('resize',()=>this.resizeCanvas());for(let i=0;i<100;i++){this.particles.push({x:Math.random()*this.canvas.width,y:Math.random()*this.canvas.height,vx:(Math.random()-0.5)*0.5,vy:(Math.random()-0.5)*0.5,size:Math.random()*3+1,opacity:Math.random()*0.5+0.2});}},resizeCanvas(){this.canvas.width=window.innerWidth;this.canvas.height=window.innerHeight;},animateParticles(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height);this.particles.forEach((p,i)=>{p.x+=p.vx;p.y+=p.vy;if(p.x<0||p.x>this.canvas.width)p.vx*=-1;if(p.y<0||p.y>this.canvas.height)p.vy*=-1;this.ctx.beginPath();this.ctx.arc(p.x,p.y,p.size,0,Math.PI*2);this.ctx.fillStyle=`rgba(59,130,246,${p.opacity})`;this.ctx.fill();for(let j=i+1;j<this.particles.length;j++){const p2=this.particles[j],dx=p.x-p2.x,dy=p.y-p2.y,dist=Math.sqrt(dx*dx+dy*dy);if(dist<100){this.ctx.beginPath();this.ctx.moveTo(p.x,p.y);this.ctx.lineTo(p2.x,p2.y);this.ctx.strokeStyle=`rgba(59,130,246,${0.1*(1-dist/100)})`;this.ctx.stroke();}}});requestAnimationFrame(()=>this.animateParticles());},toggleSidebar(){document.getElementById('sidebar').classList.toggle('sidebar-hidden');},renderTools(){const tools=[{icon:'fa-image',name:'تصویر',action:'image'},{icon:'fa-microphone',name:'صدا',action:'voice'},{icon:'fa-video',name:'ویدیو',action:'video'},{icon:'fa-language',name:'ترجمه',action:'translate'},{icon:'fa-code',name:'کد',action:'code'},{icon:'fa-search',name:'جستجو',action:'search'},{icon:'fa-calculator',name:'محاسبه',action:'calculate'},{icon:'fa-file-alt',name:'مستندات',action:'docs'}];document.getElementById('tools-grid').innerHTML=tools.map(t=>`<button onclick="app.agent.quickAction('${t.action}')" class="tool-card glass p-3 rounded-xl flex flex-col items-center gap-2"><i class="fas ${t.icon} text-blue-400 text-lg"></i><span class="text-xs text-gray-400">${t.name}</span></button>`).join('');},setTheme(theme){if(theme==='light'){document.body.style.background='linear-gradient(135deg,#f0f4f8 0%,#e2e8f0 50%,#f0f4f8 100%)';document.body.style.color='#1e293b';}else{document.body.style.background='linear-gradient(135deg,#0f172a 0%,#1e293b 50%,#0f172a 100%)';document.body.style.color='#e2e8f0';}},loadSettings(){const s=JSON.parse(localStorage.getItem('kokab-settings')||'{}');if(s.theme)this.setTheme(s.theme);if(s.openrouterKey)document.getElementById('openrouter-key').value=s.openrouterKey;if(s.hfKey)document.getElementById('hf-key').value=s.hfKey;if(s.ttsEnabled!==undefined)document.getElementById('tts-enabled').checked=s.ttsEnabled;},scrollToBottom(){const c=document.getElementById('chat-container');c.scrollTop=c.scrollHeight;},showToast(msg,type='info'){const toast=document.getElementById('toast'),icons={success:'fa-check-circle text-green-500',error:'fa-exclamation-circle text-red-500',info:'fa-info-circle text-blue-500'};document.getElementById('toast-message').textContent=msg;document.getElementById('toast-icon').className=`fas ${icons[type]}`;toast.classList.remove('hidden');setTimeout(()=>toast.classList.add('hidden'),3000);}};
// ==================== AGENT 2: API Connection Engineer ====================
const APIAgent={async callLLM(prompt,model='mock'){try{if(model==='hf-free')return await this.callHF(prompt);if(model==='hf-openrouter')return await this.callOpenRouter(prompt);return await this.mock(prompt);}catch(e){throw new Error(`خطا API: ${e.message}`);}},async callHF(prompt){const key=localStorage.getItem('kokab-hf-key')||'';const res=await fetch('https://corsproxy.io/?'+encodeURIComponent('https://api-inference.huggingface.co/models/gpt2'),{method:'POST',headers:{'Content-Type':'application/json',...(key?{Authorization:`Bearer ${key}`}:{})},body:JSON.stringify({inputs:prompt,parameters:{max_new_tokens:500,temperature:0.7}})});if(!res.ok)throw new Error(`HTTP ${res.status}`);const data=await res.json();return data[0]?.generated_text||'پاسخی دریافت نشد';},async callOpenRouter(prompt){const key=localStorage.getItem('kokab-openrouter-key');if(!key)throw new Error('کلید OpenRouter تنظیم نشده');const res=await fetch('https://corsproxy.io/?'+encodeURIComponent('https://openrouter.ai/api/v1/chat/completions'),{method:'POST',headers:{'Content-Type':'application/json',Authorization:`Bearer ${key}`,'HTTP-Referer':location.href,'X-Title':'Kokab'},body:JSON.stringify({model:'google/gemma-2-9b-it:free',messages:[{role:'system',content:'You are Kokab, respond in Persian.'},{role:'user',content:prompt}],max_tokens:1000})});if(!res.ok)throw new Error(`HTTP ${res.status}`);const data=await res.json();return data.choices?.[0]?.message?.content||'پاسخی دریافت نشد';},async mock(prompt){await new Promise(r=>setTimeout(r,800));return`پاسخ آزمایشی به: "${prompt.substring(0,30)}..."\n\nبرای پاسخ واقعی، کلید API تنظیم کنید.`;}};
// ==================== AGENT 3: Tools Specialist ====================
const ToolsAgent={attachedFiles:[],tools:{image:async(p)=>{const f=p.file||ToolsAgent.attachedFiles[0];if(!f)return'تصویری آپلود نشده';return new Promise(r=>{const reader=new FileReader();reader.onload=e=>r(`تصویر: ${f.name}\n\n![img](${e.target.result})`);reader.readAsDataURL(f);});},voice:async()=> 'ضبط صدا فعال شد...',video:async()=> 'پردازش ویدیو نیاز به backend دارد.',translate:async(p)=>{const t=p.text||'متن وارد کنید';return`ترجمه: ${t}`;},code:async(p)=>{return`\`\`\`javascript\n// ${p.desc||'کد نمونه'}\nfunction hello(){console.log("Kokab");}\n\`\`\``;},search:async(p)=>`جستجو برای: ${p.query||''}`,calculate:async(p)=>{try{const r=Function('"use strict";return('+p.exp+')')();return`نتیجه: ${p.exp}=${r}`;}catch{return'خطای محاسبه';}},docs:async()=>'📚 مستندات ابرهوش کوکب'},async executeTool(name,params={}){return this.tools[name]?await this.tools[name](params):`ابزار "${name}" یافت نشد`;},handleFileSelect(e){this.attachedFiles.push(...Array.from(e.target.files));this.renderPreview();},renderPreview(){document.getElementById('files-preview').innerHTML=this.attachedFiles.map((f,i)=>`<div class="glass px-3 py-2 rounded-lg flex items-center gap-2"><i class="fas fa-file text-blue-400"></i><span class="text-xs truncate max-w-[150px]">${f.name}</span><button onclick="app.tools.removeFile(${i})" class="text-red-400"><i class="fas fa-times"></i></button></div>`).join('');},removeFile(i){this.attachedFiles.splice(i,1);this.renderPreview();},clearFiles(){this.attachedFiles=[];this.renderPreview();document.getElementById('file-input').value='';}};
// ==================== AGENT 4: Agent Core ====================
const AgentCore={history:[],async processMessage(msg){this.history.push({role:'user',content:msg,ts:Date.now()});const intent=this.analyzeIntent(msg);if(intent.tool){app.ui.showToast(`فراخوانی: ${intent.tool}`,'info');const result=await ToolsAgent.executeTool(intent.tool,intent.params);const enhanced=`${msg}\n\n[نتیجه ابزار]: ${result}`;const resp=await APIAgent.callLLM(enhanced,document.getElementById('model-select').value);this.history.push({role:'assistant',content:resp,ts:Date.now()});return resp;}const ctx=this.buildContext(msg);const resp=await APIAgent.callLLM(ctx,document.getElementById('model-select').value);this.history.push({role:'assistant',content:resp,ts:Date.now()});return resp;},analyzeIntent(msg){const l=msg.toLowerCase();if(l.includes('عکس')||l.includes('تصویر'))return ToolsAgent.attachedFiles.some(f=>f.type.startsWith('image/'))?{tool:'image',params:{}}:{};if(l.includes('ترجمه'))return{tool:'translate',params:{text:msg}};if(l.includes('کد'))return{tool:'code',params:{desc:msg}};if(l.match(/[\d+\-*/.=]+/)){const m=l.match(/([\d+\-*/(). ]+)/);if(m)return{tool:'calculate',params:{exp:m[1]}};}return{tool:null,params:{}};},buildContext(msg){const recent=this.history.slice(-10);return`شما کوکب هستید، دستیار فارسی.\n\n${recent.map(m=>`${m.role==='user'?'کاربر':'کوکب'}: ${m.content}`).join('\n')}\nکاربر: ${msg}\nکوکب:`;},quickAction(a){const p={'تحلیل تصویر':'این تصویر را تحلیل کن','ترجمه':'ترجمه کن: ','خلاصه':'خلاصه کن: ','کدنویسی':'کد بنویس برای: ','محاسبه':'محاسبه کن: '};const i=document.getElementById('user-input');i.value=p[a]||a;i.focus();}};
// ==================== AGENT 5: Voice Specialist ====================
const VoiceAgent={recorder:null,chunks:[],recording:false,async initRecognition(){if('webkitSpeechRecognition'in window||'SpeechRecognition'in window){const SR=window.SpeechRecognition||window.webkitSpeechRecognition;const rec=new SR();rec.lang='fa-IR';rec.continuous=false;rec.onresult=e=>{document.getElementById('user-input').value+=e.results[0][0].transcript;app.ui.showToast('صدا به متن تبدیل شد','success');};rec.onerror=()=>app.ui.showToast('خطای تشخیص صدا','error');return rec;}return null;},toggleRecording(){this.recording?this.stop():this.start();},async start(){try{const stream=await navigator.mediaDevices.getUserMedia({audio:true});this.recorder=new MediaRecorder(stream);this.chunks=[];this.recorder.ondataavailable=e=>this.chunks.push(e.data);this.recorder.onstop=()=>{new Blob(this.chunks,{type:'audio/wav'});app.ui.showToast('ضبط 완료','success');};this.recorder.start();this.recording=true;app.ui.showToast('در حال ضبط...','info');}catch(e){app.ui.showToast('دسترسی میکروفون نیاز است','error');}},stop(){if(this.recorder&&this.recording){this.recorder.stop();this.recording=false;}},speak(text){if(!document.getElementById('tts-enabled')?.checked)return;if('speechSynthesis'in window){const u=new SpeechSynthesisUtterance(text);u.lang='fa-IR';u.rate=0.9;speechSynthesis.speak(u);}}};
// ==================== AGENT 6: Data Engineer ====================
const DataAgent={saveChat(){localStorage.setItem('kokab-chat-history',JSON.stringify(AgentCore.history));},loadChat(){const s=localStorage.getItem('kokab-chat-history');if(s)AgentCore.history=JSON.parse(s);},exportChat(){const c=AgentCore.history.map(m=>`[${new Date(m.ts).toLocaleString('fa-IR')}] ${m.role==='user'?'کاربر':'کوکب'}: ${m.content}`).join('\n\n');const blob=new Blob([c],{type:'text/plain;charset=utf-8'}),url=URL.createObjectURL(blob),a=document.createElement('a');a.href=url;a.download=`kokab-${Date.now()}.txt`;a.click();URL.revokeObjectURL(url);app.ui.showToast('خروجی گرفته شد','success');},clearChat(){AgentCore.history=[];localStorage.removeItem('kokab-chat-history');document.getElementById('chat-container').innerHTML='';app.ui.showToast('پاک شد','success');},saveSettings(){const s={openrouterKey:document.getElementById('openrouter-key').value,hfKey:document.getElementById('hf-key').value,ttsEnabled:document.getElementById('tts-enabled').checked,theme:'dark'};localStorage.setItem('kokab-settings',JSON.stringify(s));if(s.openrouterKey)localStorage.setItem('kokab-openrouter-key',s.openrouterKey);if(s.hfKey)localStorage.setItem('kokab-hf-key',s.hfKey);}};
// ==================== AGENT 7: Quality Manager ====================
const QualityAgent={runTests(){console.log('Tests: OK');},validateInput(i){if(!i||!i.trim()){app.ui.showToast('پیام خالی است','error');return false;}if(i.length>10000){app.ui.showToast('پیام طولانی است','error');return false;}return true;},handleError(e,c){console.error(`Error ${c}:`,e);app.ui.showToast(`خطا: ${e.message}`,'error');}};
// ==================== Main App ====================
const app={ui:UIAgent,api:APIAgent,tools:ToolsAgent,agent:AgentCore,voice:VoiceAgent,DataAgent,qa:QualityAgent,init(){this.ui.init();this.data.loadChat();this.qa.runTests();const rec=this.voice.initRecognition();if(rec)document.querySelector('.fa-microphone').parentElement.onclick=()=>{rec.start();app.ui.showToast('گوش می‌دهم...','info');};console.log('🌟 Kokab initialized');},chat:{async send(){const input=document.getElementById('user-input'),msg=input.value.trim();if(!app.qa.validateInput(msg))return;input.value='';input.style.height='auto';app.tools.clearFiles();this.addMessage('user',msg);const tid=this.showTyping();try{const resp=await app.agent.processMessage(msg);this.removeTyping(tid);this.addMessage('assistant',resp);app.data.saveChat();app.voice.speak(resp);}catch(e){this.removeTyping(tid);this.addMessage('error',`خطا: ${e.message}`);app.qa.handleError(e,'send');}},addMessage(role,content){const c=document.getElementById('chat-container'),isUser=role==='user',isError=role==='error';c.insertAdjacentHTML('beforeend',`<div class="message-enter flex gap-4 max-w-4xl mx-auto ${isUser?'flex-row-reverse':''}"><div class="w-10 h-10 rounded-full ${isUser?'bg-gradient-to-br from-green-500 to-teal-600':'bg-gradient-to-br from-blue-500 to-purple-600'} flex items-center justify-center flex-shrink-0"><i class="fas ${isUser?'fa-user':'fa-brain'} text-white"></i></div><div class="flex-1 glass rounded-2xl ${isUser?'rounded-tl-none bg-kokab-700':'rounded-tr-none'} p-4"><div class="markdown-body text-gray-300">${isError?`<span class="text-red-400">${content}</span>`:marked.parse(content)}</div><div class="text-xs text-gray-500 mt-2">${new Date().toLocaleTimeString('fa-IR')}</div></div></div>`);app.ui.scrollToBottom();},showTyping(){const id='typing-'+Date.now(),c=document.getElementById('chat-container');c.insertAdjacentHTML('beforeend',`<div id="${id}" class="flex gap-4 max-w-4xl mx-auto"><div class="w-10 h-10 rounded-full bg-gradient-to-br from-blue-500 to-purple-600 flex items-center justify-center"><i class="fas fa-brain text-white"></i></div><div class="glass rounded-2xl rounded-tr-none p-4"><div class="flex gap-1"><div class="w-2 h-2 bg-blue-400 rounded-full typing-dot"></div><div class="w-2 h-2 bg-blue-400 rounded-full typing-dot"></div><div class="w-2 h-2 bg-blue-400 rounded-full typing-dot"></div></div></div></div>`);app.ui.scrollToBottom();return id;},removeTyping(id){const e=document.getElementById(id);if(e)e.remove();},handleKeyDown(e){if(e.key==='Enter'&&!e.shiftKey){e.preventDefault();app.chat.send();}},clearHistory(){if(confirm('آیا مطمئن هستید؟')){app.data.clearChat();location.reload();}}},settings:{open(){document.getElementById('settings-modal').classList.remove('hidden');},close(){document.getElementById('settings-modal').classList.add('hidden');},save(){app.data.saveSettings();this.close();app.ui.showToast('ذخیره شد','success');}}};
document.addEventListener('DOMContentLoaded',()=>app.init());
</script>
</body>
</html>