Spaces:
Running
Running
<html lang="th"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"> | |
<title>AI Chatbot - Classic Enhanced</title> | |
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css"> | |
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> | |
<link href="https://fonts.googleapis.com/css2?family=Courier+Prime:wght@400;700&family=Roboto+Mono:wght@300;400&display=swap" rel="stylesheet"> | |
<style> | |
:root { | |
--bg-primary: #1a1a1a; /* น้ำตาลเข้ม/ดำ */ | |
--bg-secondary: #2c2c2c; /* น้ำตาลเข้ม/ดำ (สว่างขึ้น) */ | |
--bg-tertiary: #3d3d3d; /* น้ำตาลเข้ม/ดำ (สว่างสุด) */ | |
--text-primary: #f0e6d2; /* ครีม/สว่าง */ | |
--text-secondary: #a0937d; /* ครีม/น้ำตาล (หม่น) */ | |
--accent-primary: #33ff99; /* เขียว */ | |
--accent-secondary: #ff9933; /* ส้ม */ | |
--accent-tertiary: #8b4513; /* น้ำตาล */ | |
--chat-bg: #f5f5dc; /* ครีมสำหรับแชท */ | |
--chat-text: #333333; /* ข้อความเข้มสำหรับแชท */ | |
--error: #ff4757; | |
--success: #2ed573; | |
--glass-bg: rgba(44, 44, 44, 0.2); /* ปรับให้โปร่งใสขึ้น */ | |
--glass-border: rgba(51, 255, 153, 0.2); /* เขียวโปร่ง */ | |
--shadow-lg: 0 15px 35px rgba(0, 0, 0, 0.5); | |
--shadow-xl: 0 20px 45px rgba(0, 0, 0, 0.6); | |
--gradient-primary: linear-gradient(135deg, var(--accent-primary), var(--accent-secondary)); | |
--font-main: 'Roboto Mono', 'Courier Prime', 'Courier New', monospace; | |
--font-code: 'Courier Prime', 'Courier New', monospace; | |
} | |
* { | |
box-sizing: border-box; | |
margin: 0; | |
padding: 0; | |
-webkit-tap-highlight-color: transparent; | |
} | |
body { | |
font-family: var(--font-main); | |
background: var(--bg-primary); | |
background-image: | |
radial-gradient(ellipse at top left, rgba(51, 255, 153, 0.06) 0%, transparent 55%), | |
radial-gradient(ellipse at bottom right, rgba(255, 153, 51, 0.06) 0%, transparent 55%); | |
color: var(--text-primary); | |
display: flex; | |
justify-content: center; | |
align-items: center; | |
min-height: 100vh; | |
overflow: hidden; | |
font-weight: 300; | |
} | |
.app-container { | |
width: 95%; | |
max-width: 1400px; | |
background: var(--glass-bg); | |
backdrop-filter: blur(15px); | |
-webkit-backdrop-filter: blur(15px); | |
border: 1px solid var(--glass-border); | |
border-radius: 20px; | |
box-shadow: var(--shadow-xl); | |
display: flex; | |
overflow: hidden; | |
height: 90vh; | |
position: relative; | |
animation: slideIn 0.8s cubic-bezier(0.23, 1, 0.32, 1); | |
} | |
@keyframes slideIn { | |
from { opacity: 0; transform: translateY(40px) scale(0.97); } | |
to { opacity: 1; transform: translateY(0) scale(1); } | |
} | |
.settings-panel { | |
width: 320px; | |
padding: 25px; | |
background: rgba(30, 30, 30, 0.5); | |
backdrop-filter: blur(10px); | |
border-right: 1px solid var(--glass-border); | |
transition: all 0.4s cubic-bezier(0.23, 1, 0.32, 1); | |
overflow-y: auto; | |
scrollbar-width: thin; | |
scrollbar-color: var(--accent-primary) transparent; | |
} | |
.settings-panel.collapsed { width: 0; padding: 0; overflow: hidden; border-right: none; } | |
.settings-panel::-webkit-scrollbar { width: 6px; } | |
.settings-panel::-webkit-scrollbar-track { background: transparent; } | |
.settings-panel::-webkit-scrollbar-thumb { background: var(--accent-primary); border-radius: 3px; } | |
.main-content { | |
flex: 1; | |
display: flex; | |
flex-direction: column; | |
position: relative; | |
background: transparent; | |
} | |
h2 { | |
font-size: 1.3rem; | |
margin-bottom: 25px; | |
font-weight: 400; | |
background: var(--gradient-primary); | |
-webkit-background-clip: text; | |
-webkit-text-fill-color: transparent; | |
background-clip: text; | |
text-fill-color: transparent; | |
padding-bottom: 5px; | |
border-bottom: 1px solid var(--glass-border); | |
} | |
.form-field { margin-bottom: 20px; } | |
.form-field label { | |
display: block; margin-bottom: 8px; font-size: 0.9rem; | |
font-weight: 400; color: var(--text-secondary); | |
text-transform: uppercase; letter-spacing: 0.5px; | |
} | |
.form-field select, .form-field textarea { | |
width: 100%; padding: 12px 16px; border: 1px solid var(--glass-border); | |
border-radius: 8px; background: var(--bg-tertiary); | |
color: var(--text-primary); font-size: 0.95rem; | |
transition: all 0.3s ease; font-family: var(--font-main); | |
} | |
.form-field select:focus, .form-field textarea:focus { | |
outline: none; border-color: var(--accent-primary); | |
box-shadow: 0 0 15px var(--accent-primary); | |
} | |
.form-field textarea { resize: vertical; min-height: 100px; } | |
button { | |
padding: 12px 24px; border: 1px solid var(--accent-primary); | |
border-radius: 8px; background: var(--accent-primary); | |
color: var(--bg-primary); cursor: pointer; | |
font-size: 1rem; font-weight: 700; | |
transition: all 0.3s ease; touch-action: manipulation; | |
font-family: var(--font-main); | |
} | |
button:hover { | |
background: transparent; color: var(--accent-primary); | |
box-shadow: 0 0 10px var(--accent-primary); | |
transform: translateY(-2px); | |
} | |
button:active { transform: translateY(0px) scale(0.98); } | |
.material-icons { font-size: 24px; vertical-align: middle; } | |
.chat-container { | |
flex: 1; padding: 25px; overflow-y: auto; display: flex; | |
flex-direction: column; gap: 16px; | |
background: var(--chat-bg); /* Cream Background */ | |
color: var(--chat-text); | |
scrollbar-width: thin; scrollbar-color: var(--accent-secondary) transparent; | |
} | |
.chat-container::-webkit-scrollbar { width: 8px; } | |
.chat-container::-webkit-scrollbar-track { background: transparent; } | |
.chat-container::-webkit-scrollbar-thumb { background: var(--accent-secondary); border-radius: 4px; } | |
.message { | |
max-width: 80%; padding: 16px 20px; border-radius: 15px; /* Softer */ | |
font-size: 1rem; line-height: 1.6; position: relative; | |
animation: messageSlide 0.5s cubic-bezier(0.23, 1, 0.32, 1); | |
font-family: 'Segoe UI', Roboto, sans-serif; /* Readable font */ | |
} | |
@keyframes messageSlide { | |
from { opacity: 0; transform: translateY(20px); } | |
to { opacity: 1; transform: translateY(0); } | |
} | |
.message.user { | |
background: linear-gradient(135deg, var(--accent-secondary), #ff6b35); | |
align-self: flex-end; box-shadow: 0 6px 15px rgba(255, 153, 51, 0.3); | |
color: #fff; | |
} | |
.message.ai { | |
background: #ffffff; border: 1px solid #e0e0e0; | |
align-self: flex-start; box-shadow: 0 6px 15px rgba(0, 0, 0, 0.1); | |
color: var(--chat-text); | |
} | |
.message.ai pre { | |
background: #1e1e1e; color: #d4d4d4; padding: 20px; | |
border-radius: 8px; overflow-x: auto; | |
border: 1px solid #333; margin-top: 15px; position: relative; | |
} | |
.message.ai pre code { font-family: var(--font-code); font-size: 0.9rem; } | |
.code-tools { | |
position: absolute; top: 10px; right: 10px; display: flex; gap: 8px; | |
opacity: 0; transition: opacity 0.3s ease; | |
} | |
pre:hover .code-tools { opacity: 1; } | |
.code-tools button { | |
padding: 6px 10px; font-size: 0.8rem; background: #333; | |
color: var(--accent-green); border: 1px solid var(--accent-green); | |
} | |
.code-tools button:hover { background: var(--accent-green); color: #1e1e1e; } | |
.input-container { | |
display: flex; gap: 12px; padding: 20px; | |
background: rgba(30, 30, 30, 0.6); backdrop-filter: blur(10px); | |
border-top: 1px solid var(--glass-border); align-items: center; | |
} | |
#userInput { | |
flex: 1; padding: 16px 20px; border: 1px solid var(--glass-border); | |
border-radius: 10px; background: var(--bg-secondary); | |
color: var(--text-primary); resize: none; min-height: 58px; | |
max-height: 150px; font-size: 1rem; transition: all 0.3s ease; | |
} | |
#userInput:focus { | |
outline: none; border-color: var(--accent-primary); | |
box-shadow: 0 0 20px var(--accent-primary); | |
} | |
.input-btn { | |
display: flex; align-items: center; justify-content: center; | |
width: 58px; height: 58px; border-radius: 50%; /* Round buttons */ | |
background: var(--bg-tertiary); color: var(--accent-primary); | |
transition: all 0.3s ease; padding: 0; | |
border: 1px solid var(--accent-primary); | |
} | |
.input-btn:hover { | |
background: var(--accent-primary); color: var(--bg-primary); | |
transform: scale(1.05); box-shadow: 0 0 15px var(--accent-primary); | |
} | |
.input-btn:disabled { | |
background: var(--bg-tertiary); cursor: not-allowed; | |
transform: none; box-shadow: none; opacity: 0.5; | |
border-color: #555; color: #555; | |
} | |
.spinner { | |
width: 26px; height: 26px; border: 3px solid rgba(51, 255, 153, 0.3); | |
border-top: 3px solid var(--accent-primary); border-radius: 50%; | |
animation: spin 1s linear infinite; | |
} | |
@keyframes spin { to { transform: rotate(360deg); } } | |
.mode-toggle { | |
display: flex; background: var(--bg-secondary); | |
border-radius: 15px; padding: 4px; position: relative; | |
margin: 15px 20px; border: 1px solid var(--glass-border); | |
} | |
.mode-toggle button { | |
flex: 1; padding: 10px 18px; background: none; border: none; | |
color: var(--text-secondary); cursor: pointer; z-index: 1; | |
font-size: 0.9rem; font-weight: 600; border-radius: 12px; | |
transition: color 0.4s ease; box-shadow: none; | |
} | |
.mode-toggle button.active { color: var(--text-primary); } | |
.mode-toggle-slider { | |
position: absolute; top: 4px; left: 4px; height: calc(100% - 8px); | |
background: var(--gradient-primary); border-radius: 12px; | |
transition: all 0.4s cubic-bezier(0.23, 1, 0.32, 1); | |
box-shadow: 0 4px 15px rgba(51, 255, 153, 0.3); | |
width: calc(50% - 4px); /* Corrected width */ | |
} | |
/* --- Carousel (Original Layout) --- */ | |
.carousel-container { | |
perspective: 1200px; height: 100%; display: flex; flex-direction: column; | |
align-items: center; justify-content: center; position: relative; | |
user-select: none; padding: 24px; flex: 1; /* Ensure it fills space */ | |
} | |
.carousel { | |
position: relative; width: 90%; max-width: 500px; height: 300px; | |
transform-style: preserve-3d; | |
transition: transform 0.6s cubic-bezier(0.23, 1, 0.32, 1); | |
cursor: grab; | |
} | |
.carousel.dragging { cursor: grabbing; } | |
.carousel-card { | |
position: absolute; width: 100%; height: 100%; | |
background: var(--bg-secondary); backdrop-filter: blur(10px); | |
border: 1px solid var(--glass-border); border-radius: 16px; | |
padding: 24px; box-shadow: 0 10px 25px rgba(0,0,0,0.4); | |
display: flex; flex-direction: column; gap: 12px; | |
transition: all 0.6s cubic-bezier(0.23, 1, 0.32, 1); | |
backface-visibility: hidden; | |
} | |
.carousel-controls, .carousel-indicator { display: flex; gap: 16px; margin-top: 24px; } | |
.carousel-controls button { | |
padding: 10px; width: 50px; height: 50px; border-radius: 50%; | |
display: flex; align-items: center; justify-content: center; | |
background: var(--bg-tertiary); color: var(--accent-primary); | |
border: 1px solid var(--accent-primary); | |
} | |
.carousel-controls button:hover { background: var(--accent-primary); color: var(--bg-primary); } | |
.carousel-dot { | |
width: 14px; height: 14px; background: var(--bg-tertiary); | |
border-radius: 50%; cursor: pointer; transition: all 0.3s ease; | |
border: 2px solid transparent; | |
} | |
.carousel-dot.active { background: var(--accent-primary); transform: scale(1.2); } | |
.carousel-dot:hover { border-color: var(--accent-primary); } | |
#applyPromptBtn { margin-top: 24px; } | |
.chip-container { | |
display: flex; gap: 12px; margin-bottom: 20px; flex-wrap: wrap; | |
padding: 0 24px; | |
} | |
.chip { | |
padding: 10px 18px; background: var(--bg-tertiary); | |
border: 1px solid var(--glass-border); border-radius: 20px; | |
font-size: 0.85rem; font-weight: 500; cursor: pointer; | |
transition: all 0.3s ease; color: var(--text-secondary); | |
} | |
.chip:hover { | |
background: var(--accent-secondary); color: var(--bg-primary); | |
transform: translateY(-2px); box-shadow: 0 6px 15px rgba(255, 153, 51, 0.3); | |
} | |
.floating-buttons { | |
position: absolute; top: 20px; right: 20px; display: flex; | |
gap: 12px; z-index: 100; | |
} | |
.floating-btn { | |
width: 48px; height: 48px; border-radius: 50%; | |
background: var(--bg-secondary); backdrop-filter: blur(10px); | |
border: 1px solid var(--glass-border); display: flex; | |
align-items: center; justify-content: center; | |
transition: all 0.3s ease; padding: 0; color: var(--text-primary); | |
} | |
.floating-btn:hover { | |
background: var(--accent-primary); color: var(--bg-primary); | |
transform: scale(1.1); box-shadow: 0 0 15px var(--accent-primary); | |
} | |
#chatMode { display: none; flex: 1; flex-direction: column; } | |
#carouselMode { display: flex; flex: 1; flex-direction: column; } | |
@media (max-width: 768px) { | |
.app-container { flex-direction: column; height: 100vh; border-radius: 0; } | |
.settings-panel { width: 100%; max-height: 40vh; border-right: none; border-bottom: 1px solid var(--glass-border); } | |
.settings-panel.collapsed { max-height: 0; } | |
.carousel { height: 250px; } | |
.floating-buttons { top: 15px; right: 15px; } | |
} | |
</style> | |
</head> | |
<body> | |
<div class="app-container" id="appContainer"> | |
<div class="settings-panel" id="settingsPanel"> | |
<h2>⚙️ ตั้งค่า</h2> | |
<div class="form-field"> | |
<label>🤖 โมเดลหลัก:</label> | |
<select id="modelSelect"> | |
<option value="Qwen/Qwen2.5-Coder-32B-Instruct">Qwen2.5-Coder 32B</option> | |
<option value="Qwen/Qwen2-VL-72B-Instruct">Qwen2-VL 72B (Image)</option> | |
<option value="microsoft/Florence-2-large">Florence-2 Large (Image)</option> | |
</select> | |
<p style="font-size: 0.8rem; color: var(--text-secondary); margin-top: 8px;"> | |
💡 เลือกโมเดล (VL/Florence สำหรับรูปภาพ) | |
</p> | |
</div> | |
<div class="form-field"> | |
<label>👁️ โมเดล OCR:</label> | |
<select id="ocrModelSelect"> | |
<option value="none">ไม่ใช้</option> | |
<option value="microsoft/trocr-base-printed">TrOCR Base</option> | |
</select> | |
</div> | |
<button id="saveSettingsBtn">💾 บันทึก</button> | |
</div> | |
<div class="main-content"> | |
<div class="floating-buttons"> | |
<button id="settingsToggle" class="floating-btn"><span class="material-icons">settings</span></button> | |
<button id="fullscreenToggle" class="floating-btn"><span class="material-icons">fullscreen</span></button> | |
<button id="refreshBtn" class="floating-btn"><span class="material-icons">refresh</span></button> | |
</div> | |
<div class="mode-toggle"> | |
<button id="carouselModeBtn" class="active">🎛️ Prompt Editor</button> | |
<button id="chatModeBtn">💬 แชท</button> | |
<div class="mode-toggle-slider" id="modeToggleSlider"></div> | |
</div> | |
<div id="carouselMode"> | |
<div class="carousel-container"> | |
<div class="carousel" id="promptCarousel"> | |
</div> | |
<div class="carousel-controls"> | |
<button id="prevCard"><span class="material-icons">chevron_left</span></button> | |
<button id="nextCard"><span class="material-icons">chevron_right</span></button> | |
</div> | |
<div class="carousel-indicator" id="carouselIndicator"> | |
</div> | |
<button id="applyPromptBtn">✅ ใช้ Prompt & ไปที่แชท</button> | |
</div> | |
</div> | |
<div id="chatMode"> | |
<div class="chip-container" id="quickPrompts"> | |
<span class="chip" data-prompt="อธิบายโค้ดนี้">🔍 อธิบาย</span> | |
<span class="chip" data-prompt="สร้างฟังก์ชัน">⚡ สร้าง</span> | |
<span class="chip" data-prompt="แก้บั๊ก">🐛 แก้บั๊ก</span> | |
<span class="chip" data-prompt="ปรับปรุง">🚀 ปรับปรุง</span> | |
</div> | |
<div class="chat-container" id="chatContainer"> | |
<div class="message ai">สวัสดี! กลับมาแล้ว พร้อมช่วยเหลือคุณ.</div> | |
</div> | |
<div class="input-container"> | |
<button id="attachButton" class="input-btn"><span class="material-icons">attach_file</span></button> | |
<input type="file" id="fileInput" multiple accept="image/*" style="display: none;"> | |
<span id="fileName" style="font-size: 0.8rem; color: var(--accent-primary); overflow: hidden; white-space: nowrap; text-overflow: ellipsis; max-width: 100px;"></span> | |
<textarea id="userInput" placeholder="พิมพ์ข้อความ..."></textarea> | |
<button id="sendButton" class="input-btn"><span class="material-icons">send</span></button> | |
</div> | |
</div> | |
</div> | |
</div> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/marked/9.1.6/marked.min.js"></script> | |
<script> | |
// Set up the Hugging Face API Token | |
const HUGGINGFACE_TOKEN = "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"; | |
let attachedFiles = []; | |
let currentCarouselIndex = 0; | |
let isLoading = false; | |
let carouselElement; | |
// Default prompts for the carousel | |
const prompts = [ | |
{ id: 'primarySystemPrompt', label: '🎯 Primary System Prompt', value: 'You are a powerful AI assistant that excels at understanding code, images, and technical content. Provide clear, accurate, and helpful responses. Focus on practical solutions and detailed explanations.' }, | |
{ id: 'ocrSystemPrompt', label: '👁️ OCR System Prompt', value: 'Extract all text from the provided image clearly and accurately. Preserve formatting, structure, and layout when possible. If text is unclear, indicate uncertain parts.' }, | |
{ id: 'codeTemplate', label: '💻 Code Template', value: '```javascript\n// Enhanced code implementation\nfunction solution() {\n // Your optimized code here\n return result;\n}\n```' }, | |
{ id: 'additionalInstructions', label: '📋 Additional Instructions', value: 'Always provide working, tested code examples. Include error handling and optimization suggestions. Explain complex concepts step by step. Use modern best practices.' }, | |
{ id: 'promptPrefix', label: '🚀 Prompt Prefix', value: 'Please analyze the following request carefully and provide a comprehensive solution:' }, | |
{ id: 'promptSuffix', label: '✨ Prompt Suffix', value: 'Ensure your response is complete, accurate, and includes practical examples where applicable.' } | |
]; | |
document.addEventListener('DOMContentLoaded', () => { | |
carouselElement = document.getElementById('promptCarousel'); | |
populateCarousel(); | |
loadSettings(); | |
setupEventListeners(); | |
updateCarouselPosition(); | |
switchMode('carousel'); // Start with carousel | |
}); | |
// Populates the carousel with prompt cards and navigation dots | |
function populateCarousel() { | |
const carousel = document.getElementById('promptCarousel'); | |
const indicator = document.getElementById('carouselIndicator'); | |
carousel.innerHTML = ''; | |
indicator.innerHTML = ''; | |
const totalCards = prompts.length; | |
const anglePerCard = 360 / totalCards; | |
const cardWidth = 500; // Based on max-width | |
const translateZ = (cardWidth / 2) / Math.tan((anglePerCard / 2) * (Math.PI / 180)); | |
prompts.forEach((prompt, index) => { | |
const card = document.createElement('div'); | |
card.className = 'carousel-card'; | |
const angle = index * anglePerCard; | |
card.style.transform = `rotateY(${angle}deg) translateZ(${translateZ}px)`; | |
card.innerHTML = ` | |
<label>${prompt.label}</label> | |
<textarea id="${prompt.id}" placeholder="Enter prompt...">${localStorage.getItem(prompt.id) || prompt.value}</textarea> | |
`; | |
carousel.appendChild(card); | |
const dot = document.createElement('div'); | |
dot.className = 'carousel-dot'; | |
dot.dataset.index = index; | |
indicator.appendChild(dot); | |
}); | |
carousel.dataset.translateZ = translateZ; // Store for later use | |
} | |
// Loads saved settings from local storage | |
function loadSettings() { | |
document.getElementById('modelSelect').value = localStorage.getItem('selectedModel') || 'Qwen/Qwen2.5-Coder-32B-Instruct'; | |
document.getElementById('ocrModelSelect').value = localStorage.getItem('selectedOcrModel') || 'none'; | |
// Prompt values are loaded directly in populateCarousel | |
} | |
// Saves current settings to local storage | |
function saveSettings() { | |
localStorage.setItem('selectedModel', document.getElementById('modelSelect').value); | |
localStorage.setItem('selectedOcrModel', document.getElementById('ocrModelSelect').value); | |
prompts.forEach(p => localStorage.setItem(p.id, document.getElementById(p.id).value)); | |
showNotification('บันทึกแล้ว!', 'success'); | |
} | |
// Sets up all event listeners for interactive elements | |
function setupEventListeners() { | |
document.getElementById('carouselModeBtn').addEventListener('click', () => switchMode('carousel')); | |
document.getElementById('chatModeBtn').addEventListener('click', () => switchMode('chat')); | |
document.getElementById('saveSettingsBtn').addEventListener('click', saveSettings); | |
document.getElementById('settingsToggle').addEventListener('click', () => document.getElementById('settingsPanel').classList.toggle('collapsed')); | |
document.getElementById('prevCard').addEventListener('click', () => rotateCarousel(-1)); | |
document.getElementById('nextCard').addEventListener('click', () => rotateCarousel(1)); | |
document.getElementById('applyPromptBtn').addEventListener('click', applyPromptsAndSwitchToChat); | |
document.getElementById('sendButton').addEventListener('click', sendMessage); | |
document.getElementById('attachButton').addEventListener('click', () => document.getElementById('fileInput').click()); | |
document.getElementById('fileInput').addEventListener('change', handleFileSelect); | |
document.getElementById('userInput').addEventListener('keydown', handleKeyDown); | |
document.getElementById('fullscreenToggle').addEventListener('click', toggleFullscreen); | |
document.getElementById('refreshBtn').addEventListener('click', () => location.reload()); | |
document.querySelectorAll('.chip').forEach(chip => { | |
chip.addEventListener('click', (e) => { | |
document.getElementById('userInput').value = e.target.getAttribute('data-prompt'); | |
document.getElementById('userInput').focus(); | |
}); | |
}); | |
document.querySelectorAll('.carousel-dot').forEach(dot => { | |
dot.addEventListener('click', (e) => goToCarouselIndex(parseInt(e.target.dataset.index))); | |
}); | |
// Basic Touch Swipe for Carousel | |
let touchStartX = 0; | |
let touchEndX = 0; | |
carouselElement.addEventListener('touchstart', e => { touchStartX = e.changedTouches[0].screenX; }, { passive: true }); | |
carouselElement.addEventListener('touchend', e => { | |
touchEndX = e.changedTouches[0].screenX; | |
handleSwipe(); | |
}, { passive: true }); | |
function handleSwipe() { | |
const swipeThreshold = 50; // Minimum distance for a swipe | |
if (touchEndX < touchStartX - swipeThreshold) rotateCarousel(1); // Swipe left -> Next | |
if (touchEndX > touchStartX + swipeThreshold) rotateCarousel(-1); // Swipe right -> Prev | |
} | |
} | |
// Switches between carousel and chat modes | |
function switchMode(mode) { | |
const carouselMode = document.getElementById('carouselMode'); | |
const chatMode = document.getElementById('chatMode'); | |
const carouselBtn = document.getElementById('carouselModeBtn'); | |
const chatBtn = document.getElementById('chatModeBtn'); | |
const slider = document.getElementById('modeToggleSlider'); | |
const sliderWidth = carouselBtn.offsetWidth; // Get width based on button | |
if (mode === 'carousel') { | |
carouselMode.style.display = 'flex'; | |
chatMode.style.display = 'none'; | |
carouselBtn.classList.add('active'); | |
chatBtn.classList.remove('active'); | |
slider.style.width = `${sliderWidth}px`; | |
slider.style.left = '4px'; | |
} else { | |
carouselMode.style.display = 'none'; | |
chatMode.style.display = 'flex'; | |
carouselBtn.classList.remove('active'); | |
chatBtn.classList.add('active'); | |
slider.style.width = `${chatBtn.offsetWidth}px`; | |
slider.style.left = `${carouselBtn.offsetLeft + carouselBtn.offsetWidth - chatBtn.offsetWidth + 4}px`; | |
} | |
} | |
// Rotates the carousel by one card in the given direction | |
function rotateCarousel(direction) { | |
const totalCards = prompts.length; | |
currentCarouselIndex = (currentCarouselIndex + direction + totalCards) % totalCards; | |
updateCarouselPosition(); | |
} | |
// Jumps to a specific carousel card by index | |
function goToCarouselIndex(index) { | |
currentCarouselIndex = index; | |
updateCarouselPosition(); | |
} | |
// Updates the visual position of the carousel based on currentCarouselIndex | |
function updateCarouselPosition() { | |
const totalCards = prompts.length; | |
const anglePerCard = 360 / totalCards; | |
const translateZ = parseFloat(carouselElement.dataset.translateZ || 350); | |
const rotationAngle = -currentCarouselIndex * anglePerCard; | |
carouselElement.style.transform = `translateZ(-${translateZ}px) rotateY(${rotationAngle}deg)`; | |
carouselElement.querySelectorAll('.carousel-card').forEach((card, index) => { | |
card.style.opacity = index === currentCarouselIndex ? '1' : '0.6'; | |
}); | |
document.querySelectorAll('.carousel-dot').forEach((dot, index) => { | |
dot.classList.toggle('active', index === currentCarouselIndex); | |
}); | |
} | |
// Saves prompts and switches to chat mode | |
function applyPromptsAndSwitchToChat() { | |
saveSettings(); | |
switchMode('chat'); | |
showNotification('ใช้ Prompt แล้ว!', 'success'); | |
} | |
// Handles file selection for attachments | |
function handleFileSelect(e) { | |
attachedFiles = Array.from(e.target.files); | |
updateFileDisplay(); | |
} | |
// Updates the displayed file name(s) | |
function updateFileDisplay() { | |
const fileNameEl = document.getElementById('fileName'); | |
if (attachedFiles.length === 0) fileNameEl.textContent = ''; | |
else if (attachedFiles.length === 1) fileNameEl.textContent = attachedFiles[0].name; | |
else fileNameEl.textContent = `${attachedFiles.length} ไฟล์`; | |
} | |
// Handles key presses in the user input field | |
function handleKeyDown(e) { | |
if (e.key === 'Enter' && !e.shiftKey) { | |
e.preventDefault(); | |
sendMessage(); | |
} | |
} | |
// Sends a message to the Hugging Face API | |
async function sendMessage() { | |
const userInput = document.getElementById('userInput'); | |
const message = userInput.value.trim(); | |
if (!message && attachedFiles.length === 0 || isLoading) return; // Prevent sending empty messages or while loading | |
setLoading(true); | |
const chatContainer = document.getElementById('chatContainer'); | |
const userMessage = message; | |
const currentFiles = [...attachedFiles]; // Snapshot files to send | |
userInput.value = ''; // Clear input | |
attachedFiles = []; // Clear attached files | |
updateFileDisplay(); | |
if (userMessage) addMessage(userMessage, 'user'); | |
currentFiles.forEach(file => addImageMessage(URL.createObjectURL(file), 'user')); // Display attached images | |
scrollToBottom(chatContainer); | |
try { | |
const response = await callHuggingFaceAPI(userMessage, currentFiles); | |
addMessage(response, 'ai'); | |
} catch (error) { | |
console.error('Error:', error); | |
addMessage(`ขออภัย, เกิดข้อผิดพลาด: ${error.message}`, 'ai', true); | |
showNotification(`Error: ${error.message}`, 'error'); | |
} finally { | |
setLoading(false); | |
scrollToBottom(chatContainer); | |
} | |
} | |
// Calls the Hugging Face Inference API | |
async function callHuggingFaceAPI(message, files) { | |
const model = document.getElementById('modelSelect').value; | |
const ocrModel = document.getElementById('ocrModelSelect').value; | |
let fullPrompt = `${localStorage.getItem('primarySystemPrompt')}\n\n${localStorage.getItem('promptPrefix')}\n\nUser: ${message}`; | |
if (files.length > 0) { | |
const imageData = await Promise.all(files.map(file => { | |
return new Promise((resolve) => { | |
const reader = new FileReader(); | |
reader.onloadend = () => resolve(reader.result.split(',')[1]); // Get base64 content | |
reader.readAsDataURL(file); | |
}); | |
})); | |
for (let i = 0; i < imageData.length; i++) { | |
fullPrompt += `\n\nImage:\n<img src="data:${files[i].type};base64,${imageData[i]}"/>`; | |
if (ocrModel !== 'none') { | |
try { | |
const ocrText = await performOCR(files[i], ocrModel); | |
fullPrompt += `\n\n[Image OCR Content: ${ocrText}]`; | |
} catch (ocrError) { | |
console.error(`OCR failed for file ${files[i].name}:`, ocrError); | |
fullPrompt += `\n\n[Image attached, OCR failed for this image]`; | |
} | |
} | |
} | |
} | |
fullPrompt += `\n\n${localStorage.getItem('promptSuffix')}\n\nAI:`; | |
// Adjust payload for models that support multi-modal input if necessary. | |
// For now, we're encoding images into the prompt itself for simpler integration. | |
const payload = { | |
inputs: fullPrompt, | |
parameters: { max_new_tokens: 2048, temperature: 0.6, top_p: 0.9 } | |
}; | |
const response = await fetch(`https://api-inference.huggingface.co/models/${model}`, { | |
method: 'POST', | |
headers: { 'Authorization': `Bearer ${HUGGINGFACE_TOKEN}`, 'Content-Type': 'application/json' }, | |
body: JSON.stringify(payload) | |
}); | |
if (!response.ok) { | |
const errorBody = await response.json(); // Attempt to parse JSON error | |
throw new Error(`HTTP ${response.status}: ${JSON.stringify(errorBody.error || errorBody)}`); | |
} | |
const data = await response.json(); | |
if (data.error) throw new Error(data.error); | |
let text = data[0]?.generated_text || 'No response.'; | |
// Remove the prompt from the generated text, as the API often returns the full input + output | |
return text.replace(fullPrompt, '').trim(); | |
} | |
// Performs OCR on an image file using a specified OCR model | |
async function performOCR(file, ocrModel) { | |
const response = await fetch(`https://api-inference.huggingface.co/models/${ocrModel}`, { | |
method: 'POST', | |
headers: { 'Authorization': `Bearer ${HUGGINGFACE_TOKEN}` }, | |
body: file | |
}); | |
if (!response.ok) { | |
const errorBody = await response.json(); | |
throw new Error(`OCR failed: HTTP ${response.status}: ${JSON.stringify(errorBody.error || errorBody)}`); | |
} | |
const data = await response.json(); | |
return data[0]?.generated_text || 'Could not extract text.'; | |
} | |
// Adds a text message to the chat display | |
function addMessage(content, sender, isError = false) { | |
const chatContainer = document.getElementById('chatContainer'); | |
const messageDiv = document.createElement('div'); | |
messageDiv.className = `message ${sender}`; | |
if (isError) messageDiv.style.border = '1px solid var(--error)'; | |
if (sender === 'ai') { | |
// Use marked.js for Markdown parsing | |
messageDiv.innerHTML = marked.parse(content); | |
messageDiv.querySelectorAll('pre code').forEach(block => { | |
// Highlight code blocks | |
hljs.highlightElement(block); | |
// Add copy button to code blocks | |
addCodeTools(block.parentElement); | |
}); | |
} else { | |
messageDiv.textContent = content; | |
} | |
chatContainer.appendChild(messageDiv); | |
} | |
// Adds an image message to the chat display | |
function addImageMessage(imageUrl, sender) { | |
const chatContainer = document.getElementById('chatContainer'); | |
const messageDiv = document.createElement('div'); | |
messageDiv.className = `message ${sender}`; | |
messageDiv.innerHTML = `<img src="${imageUrl}" alt="Uploaded" style="max-width: 100%; max-height: 250px; border-radius: 10px;">`; | |
chatContainer.appendChild(messageDiv); | |
} | |
// Adds copy and paste buttons to code blocks | |
function addCodeTools(preElement) { | |
const toolsDiv = document.createElement('div'); | |
toolsDiv.className = 'code-tools'; | |
const copyBtn = document.createElement('button'); | |
copyBtn.innerHTML = '<span class="material-icons" style="font-size: 16px;">content_copy</span>'; | |
copyBtn.onclick = () => { | |
navigator.clipboard.writeText(preElement.querySelector('code').innerText) | |
.then(() => showNotification('คัดลอกโค้ดแล้ว!', 'success')) | |
.catch(() => showNotification('คัดลอกไม่สำเร็จ!', 'error')); | |
}; | |
toolsDiv.appendChild(copyBtn); | |
preElement.appendChild(toolsDiv); | |
} | |
// Sets the loading state of the UI | |
function setLoading(loading) { | |
isLoading = loading; | |
const sendButton = document.getElementById('sendButton'); | |
sendButton.innerHTML = loading ? '<div class="spinner"></div>' : '<span class="material-icons">send</span>'; | |
sendButton.disabled = loading; | |
} | |
// Toggles fullscreen mode | |
function toggleFullscreen() { | |
const icon = document.querySelector('#fullscreenToggle .material-icons'); | |
if (!document.fullscreenElement) { | |
document.documentElement.requestFullscreen(); | |
icon.textContent = 'fullscreen_exit'; | |
} else { | |
document.exitFullscreen(); | |
icon.textContent = 'fullscreen'; | |
} | |
} | |
// Displays a temporary notification (can be enhanced with styled toasts) | |
function showNotification(message, type = 'success') { | |
// Simple alert for now, can be replaced with a styled div | |
console.log(`Notification (${type}): ${message}`); | |
// alert(`(${type}) ${message}`); // Uncomment for actual alerts, or implement a proper notification UI | |
} | |
// Scrolls an element to its bottom | |
function scrollToBottom(element) { | |
element.scrollTo({ top: element.scrollHeight, behavior: 'smooth' }); | |
} | |
</script> | |
</body> | |
</html> | |