Spaces:
Running
Running
File size: 50,237 Bytes
276656c 28df6f6 276656c 28df6f6 276656c 28df6f6 a98bebc 28df6f6 45dc8f1 28df6f6 276656c 28df6f6 276656c 28df6f6 276656c 28df6f6 276656c 28df6f6 276656c 28df6f6 276656c 28df6f6 276656c 28df6f6 276656c 28df6f6 276656c 28df6f6 276656c 28df6f6 276656c 28df6f6 276656c 28df6f6 276656c 28df6f6 276656c 28df6f6 276656c 28df6f6 276656c 28df6f6 276656c 28df6f6 276656c 28df6f6 276656c 28df6f6 276656c 28df6f6 276656c 28df6f6 276656c 28df6f6 276656c 28df6f6 276656c 28df6f6 276656c 28df6f6 276656c 28df6f6 276656c 28df6f6 276656c 28df6f6 276656c 28df6f6 276656c 28df6f6 276656c 28df6f6 276656c 28df6f6 276656c 28df6f6 276656c 28df6f6 276656c 28df6f6 276656c 28df6f6 276656c 28df6f6 276656c 28df6f6 276656c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 |
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ứng dụng tạo ảnh AI</title>
<script src="https://cdn.tailwindcss.com"></script>
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/12.2.1/firebase-app.js";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "AIzaSyAWpLwAvoP7mKxHJwe8NReP9AAmpDDlIz8",
authDomain: "tubepsale.firebaseapp.com",
databaseURL: "https://tubepsale.firebaseio.com",
projectId: "tubepsale",
storageBucket: "tubepsale.firebasestorage.app",
messagingSenderId: "23390990085",
appId: "1:23390990085:web:083105380021186bd2916c"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
// Khai báo và gán giá trị cho các biến
// State of the application
const state = {
uploadedImages: [],
promptData: [
{ id: 0, prompt: '', inputImage: null, outputImage: null, loading: false, promptLoading: false },
{ id: 1, prompt: '', inputImage: null, outputImage: null, loading: false, promptLoading: false },
{ id: 2, prompt: '', inputImage: null, outputImage: null, loading: false, promptLoading: false },
{ id: 3, prompt: '', inputImage: null, outputImage: null, loading: false, promptLoading: false },
],
galleryImages: [],
galleryPrompts: [],
currentPromptIdForInputSelection: null,
selectedStyle: 'default'
};
let isAuthReady = false;
async function initApp() {
try {
const app = initializeApp(firebaseConfig);
db = getFirestore(app);
auth = getAuth(app);
} catch (error) {
console.error("Lỗi khi khởi tạo Firebase:", error);
}
onAuthStateChanged(auth, async (user) => {
if (user) {
userId = user.uid;
isAuthReady = true;
console.log("Authenticated with user ID:", userId);
loadData();
loadGallery();
loadPromptGallery();
} else {
try {
if (initialAuthToken) {
await signInWithCustomToken(auth, initialAuthToken);
} else {
await signInAnonymously(auth);
}
} catch (error) {
console.error("Lỗi khi xác thực:", error);
isAuthReady = true;
}
}
updateUI();
});
}
async function saveToFirestore() {
if (!userId || !isAuthReady) return;
const docRef = doc(db, "artifacts", appId, "users", userId, "imageGenData", "prompts");
const dataToSave = {
promptData: state.promptData.map(p => ({
id: p.id,
prompt: p.prompt,
inputImage: p.inputImage,
outputImage: p.outputImage
}))
};
try {
await setDoc(docRef, dataToSave, { merge: true });
} catch (error) {
console.error("Lỗi khi lưu dữ liệu vào Firestore:", error);
}
}
async function loadData() {
if (!userId) return;
const docRef = doc(db, "artifacts", appId, "users", userId, "imageGenData", "prompts");
onSnapshot(docRef, (docSnap) => {
if (docSnap.exists()) {
const data = docSnap.data();
if (data.promptData) {
data.promptData.forEach(p => {
const index = state.promptData.findIndex(item => item.id === p.id);
if (index !== -1) {
state.promptData[index].prompt = p.prompt;
state.promptData[index].inputImage = p.inputImage;
state.promptData[index].outputImage = p.outputImage;
}
});
}
}
updateUI();
}, (error) => {
console.error("Lỗi khi tải dữ liệu từ Firestore:", error);
});
}
async function loadGallery() {
if (!userId) return;
const galleryRef = collection(db, "artifacts", appId, "users", userId, "imageGallery");
onSnapshot(galleryRef, (querySnapshot) => {
state.galleryImages = [];
querySnapshot.forEach((doc) => {
const data = doc.data();
state.galleryImages.push({ id: doc.id, image: data.image });
});
updateUI();
}, (error) => {
console.error("Lỗi khi tải thư viện ảnh:", error);
});
}
async function loadPromptGallery() {
if (!userId) return;
const promptGalleryRef = collection(db, "artifacts", appId, "users", userId, "promptGallery");
onSnapshot(promptGalleryRef, (querySnapshot) => {
state.galleryPrompts = [];
querySnapshot.forEach((doc) => {
const data = doc.data();
state.galleryPrompts.push({ id: doc.id, prompt: data.prompt });
});
updateUI();
}, (error) => {
console.error("Lỗi khi tải thư viện prompt:", error);
});
}
async function saveImageToGallery(id) {
if (!userId) {
showMessage("Vui lòng đăng nhập để lưu ảnh.", 'error');
return;
}
const image = state.promptData[id].outputImage;
if (!image) {
showMessage("Không có ảnh để lưu.", 'warning');
return;
}
const galleryRef = collection(db, "artifacts", appId, "users", userId, "imageGallery");
try {
await addDoc(galleryRef, {
image: image,
timestamp: new Date()
});
showMessage("Ảnh đã được lưu vào thư viện!", 'success');
} catch (error) {
console.error("Lỗi khi lưu ảnh vào thư viện:", error);
showMessage("Lỗi khi lưu ảnh vào thư viện.", 'error');
}
}
async function savePromptToGallery(id) {
if (!userId) {
showMessage("Vui lòng đăng nhập để lưu prompt.", 'error');
return;
}
const prompt = state.promptData[id].prompt;
if (!prompt.trim()) {
showMessage("Không có prompt để lưu.", 'warning');
return;
}
const promptGalleryRef = collection(db, "artifacts", appId, "users", userId, "promptGallery");
try {
await addDoc(promptGalleryRef, {
prompt: prompt,
timestamp: new Date()
});
showMessage("Prompt đã được lưu vào thư viện!", 'success');
} catch (error) {
console.error("Lỗi khi lưu prompt vào thư viện:", error);
showMessage("Lỗi khi lưu prompt vào thư viện.", 'error');
}
}
function updateUI() {
// Default behavior: use previous output as next input if none is set
for (let i = 1; i < state.promptData.length; i++) {
if (state.promptData[i].inputImage === null && state.promptData[i-1].outputImage !== null) {
state.promptData[i].inputImage = state.promptData[i-1].outputImage;
}
}
// Update UI for prompts and generated images
state.promptData.forEach(p => {
const promptInput = document.getElementById(`prompt-${p.id}`);
const inputImageContainer = document.getElementById(`input-image-container-${p.id}`);
const outputImageContainer = document.getElementById(`output-image-container-${p.id}`);
const generateButton = document.getElementById(`generate-btn-${p.id}`);
const autoPromptButton = document.getElementById(`auto-prompt-btn-${p.id}`);
if (promptInput) {
promptInput.value = p.prompt;
}
if (inputImageContainer) {
if (p.inputImage) {
inputImageContainer.innerHTML = `<img src="${p.inputImage}" class="w-full h-full object-contain rounded-md cursor-pointer">`;
inputImageContainer.querySelector('img').addEventListener('click', () => showModal(p.inputImage));
} else {
inputImageContainer.innerHTML = `<p class="text-sm text-gray-400">Chọn ảnh đầu vào.</p>`;
}
}
if (outputImageContainer) {
if (p.outputImage) {
outputImageContainer.innerHTML = `<img src="${p.outputImage}" class="w-full h-full object-contain rounded-md cursor-pointer">`;
outputImageContainer.querySelector('img').addEventListener('click', () => showModal(p.outputImage));
} else {
outputImageContainer.innerHTML = `<div class="w-full h-full bg-gray-200 rounded-lg flex items-center justify-center">
<svg class="h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l-4 4m6-6l-4 4m6-6a2 2 0 100 4 2 2 0 000-4z"></path></svg>
</div>`;
}
}
if (generateButton) {
if (p.loading) {
generateButton.innerHTML = `<svg class="animate-spin h-5 w-5 mr-3 text-white" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>Đang tạo ảnh...`;
generateButton.disabled = true;
} else {
generateButton.innerHTML = 'Tạo ảnh';
generateButton.disabled = !p.inputImage || !p.prompt.trim();
}
}
if (autoPromptButton) {
if (p.promptLoading) {
autoPromptButton.innerHTML = `<svg class="animate-spin h-5 w-5 mr-3 text-gray-800" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>Đang tạo...`;
autoPromptButton.disabled = true;
} else {
autoPromptButton.innerHTML = 'Tạo Prompt tự động';
autoPromptButton.disabled = !p.inputImage;
}
}
});
// Update UI for uploaded images preview
const uploadedPreviewContainer = document.getElementById('uploaded-images-preview');
if (uploadedPreviewContainer) {
uploadedPreviewContainer.innerHTML = '';
state.uploadedImages.forEach(imgUrl => {
const img = document.createElement('img');
img.src = imgUrl;
img.className = 'w-24 h-24 object-cover rounded-md shadow-md cursor-pointer transition-transform duration-200 hover:scale-110';
img.title = "Click để chọn làm ảnh đầu vào";
img.addEventListener('click', () => {
const promptId = state.currentPromptIdForInputSelection;
if (promptId !== null) {
state.promptData[promptId].inputImage = imgUrl;
updateUI();
saveToFirestore();
showMessage("Đã chọn ảnh đầu vào thành công!", 'success');
}
});
uploadedPreviewContainer.appendChild(img);
});
if (state.uploadedImages.length === 0) {
uploadedPreviewContainer.innerHTML = '<p class="text-sm text-gray-400">Các ảnh bạn tải lên sẽ hiển thị ở đây.</p>';
}
}
// Update UI for image gallery
const galleryContainer = document.getElementById('gallery-container');
if (galleryContainer) {
galleryContainer.innerHTML = '';
state.galleryImages.forEach(imgData => {
const img = document.createElement('img');
img.src = imgData.image;
img.className = 'w-24 h-24 object-cover rounded-md shadow-md cursor-pointer transition-transform duration-200 hover:scale-110';
img.title = "Click để xem toàn màn hình";
img.addEventListener('click', () => showModal(imgData.image));
galleryContainer.appendChild(img);
});
if (state.galleryImages.length === 0) {
galleryContainer.innerHTML = '<p class="text-sm text-gray-400">Ảnh đã lưu sẽ hiển thị ở đây.</p>';
}
}
// Update UI for prompt gallery
const promptGalleryContainer = document.getElementById('prompt-gallery-container');
if (promptGalleryContainer) {
promptGalleryContainer.innerHTML = '';
state.galleryPrompts.forEach(promptData => {
const promptDiv = document.createElement('div');
promptDiv.className = 'bg-gray-100 p-3 rounded-lg text-sm break-words flex justify-between items-center';
promptDiv.innerHTML = `<p>${promptData.prompt}</p>
<button data-action="copy-gallery-prompt" data-prompt="${promptData.prompt}" class="ml-4 p-2 bg-violet-200 text-violet-800 rounded-full hover:bg-violet-300 transition-colors">Sao chép</button>`;
promptGalleryContainer.appendChild(promptDiv);
});
if (state.galleryPrompts.length === 0) {
promptGalleryContainer.innerHTML = '<p class="text-sm text-gray-400">Các prompt đã lưu sẽ hiển thị ở đây.</p>';
}
}
const userIdDisplay = document.getElementById('user-id-display');
if (userIdDisplay) {
userIdDisplay.textContent = `ID người dùng: ${userId || 'Đang tải...'}`;
if (userId && !isAuthReady) {
userIdDisplay.textContent = "Đang xác thực...";
}
}
}
async function generateImage(id) {
const prompt = state.promptData[id].prompt;
const inputImage = state.promptData[id].inputImage;
const style = state.selectedStyle === 'default' ? '' : state.selectedStyle;
if (!inputImage) {
showMessage("Vui lòng chọn ảnh đầu vào trước khi tạo.", 'warning');
return;
}
if (!prompt.trim()) {
showMessage("Vui lòng nhập lời nhắc (prompt) cho hình ảnh.", 'warning');
return;
}
state.promptData[id].loading = true;
updateUI();
const fullPrompt = `${prompt}, ${style}`;
const payload = {
contents: [{
parts: [
{ text: fullPrompt },
{
inlineData: {
mimeType: "image/png",
data: inputImage.split(',')[1] // Extract Base64 data
}
}
]
}],
generationConfig: {
responseModalities: ['TEXT', 'IMAGE']
}
};
const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-image-preview:generateContent?key=`;
let retries = 0;
const maxRetries = 5;
const delay = 1000;
const fetchWithRetry = async (url, options) => {
try {
const response = await fetch(url, options);
if (!response.ok) throw new Error('API request failed');
return response;
} catch (error) {
if (retries < maxRetries) {
retries++;
await new Promise(res => setTimeout(res, delay * Math.pow(2, retries)));
return fetchWithRetry(url, options);
} else {
throw error;
}
}
};
try {
const response = await fetchWithRetry(apiUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
const result = await response.json();
const base64Data = result?.candidates?.[0]?.content?.parts?.find(p => p.inlineData)?.inlineData?.data;
if (base64Data) {
state.promptData[id].outputImage = `data:image/png;base64,${base64Data}`;
showMessage("Tạo ảnh thành công!", 'success');
} else {
throw new Error("Không nhận được dữ liệu hình ảnh.");
}
} catch (error) {
console.error("Lỗi khi tạo ảnh:", error);
showMessage("Lỗi khi tạo ảnh. Vui lòng thử lại.", 'error');
} finally {
state.promptData[id].loading = false;
updateUI();
await saveToFirestore();
}
}
async function generateAutoPrompt(id) {
const inputImage = state.promptData[id].inputImage;
if (!inputImage) {
showMessage("Vui lòng chọn ảnh đầu vào trước.", 'warning');
return;
}
state.promptData[id].promptLoading = true;
updateUI();
const payload = {
contents: [
{
parts: [
{ text: "Mô tả đối tượng, phong cách và bối cảnh của hình ảnh này bằng một lời nhắc ngắn gọn, sáng tạo và chi tiết bằng tiếng Việt, phù hợp cho mô hình tạo ảnh." },
{
inlineData: {
mimeType: "image/png",
data: inputImage.split(',')[1]
}
}
]
}
]
};
const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-05-20:generateContent?key=`;
let retries = 0;
const maxRetries = 5;
const delay = 1000;
const fetchWithRetry = async (url, options) => {
try {
const response = await fetch(url, options);
if (!response.ok) throw new Error('API request failed');
return response;
} catch (error) {
if (retries < maxRetries) {
retries++;
await new Promise(res => setTimeout(res, delay * Math.pow(2, retries)));
return fetchWithRetry(url, options);
} else {
throw error;
}
}
};
try {
const response = await fetchWithRetry(apiUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
const result = await response.json();
const generatedPrompt = result?.candidates?.[0]?.content?.parts?.[0]?.text;
if (generatedPrompt) {
state.promptData[id].prompt = generatedPrompt;
showMessage("Đã tạo prompt tự động!", 'success');
} else {
throw new Error("Không nhận được prompt.");
}
} catch (error) {
console.error("Lỗi khi tạo prompt tự động:", error);
showMessage("Lỗi khi tạo prompt tự động. Vui lòng thử lại.", 'error');
} finally {
state.promptData[id].promptLoading = false;
updateUI();
await saveToFirestore();
}
}
function copyToClipboard(text) {
if (!text.trim()) {
showMessage("Không có nội dung để sao chép.", 'warning');
return;
}
navigator.clipboard.writeText(text).then(() => {
showMessage("Đã sao chép!", 'success');
}).catch(err => {
console.error('Lỗi khi sao chép:', err);
showMessage("Lỗi khi sao chép.", 'error');
});
}
function handleFileSelect(event) {
const files = event.target.files;
if (files.length === 0) return;
state.uploadedImages = [];
let filesProcessed = 0;
for (let i = 0; i < files.length; i++) {
const file = files[i];
if (file.type.startsWith('image/')) {
const reader = new FileReader();
reader.onload = (e) => {
state.uploadedImages.push(e.target.result);
filesProcessed++;
if (filesProcessed === files.length) {
updateUI();
showMessage("Đã tải ảnh lên thành công!", "success");
}
};
reader.readAsDataURL(file);
}
}
}
let messageTimeout;
function showMessage(message, type = 'info') {
const messageBox = document.getElementById('message-box');
if (!messageBox) return;
messageBox.textContent = message;
messageBox.className = 'fixed top-4 right-4 z-50 p-4 rounded-lg shadow-lg transition-all duration-300 transform translate-y-0 opacity-100 cursor-pointer';
switch(type) {
case 'error':
messageBox.classList.add('bg-red-500', 'text-white');
break;
case 'warning':
messageBox.classList.add('bg-yellow-500', 'text-white');
break;
case 'success':
messageBox.classList.add('bg-green-500', 'text-white');
break;
default:
messageBox.classList.add('bg-blue-500', 'text-white');
}
clearTimeout(messageTimeout);
if (type !== 'error' && type !== 'warning') {
messageTimeout = setTimeout(() => {
hideMessage();
}, 3000);
}
}
function hideMessage() {
const messageBox = document.getElementById('message-box');
if (messageBox) {
messageBox.className = 'fixed top-4 right-4 z-50 p-4 rounded-lg shadow-lg transition-all duration-300 transform -translate-y-full opacity-0';
}
}
function showModal(imageUrl) {
const modal = document.getElementById('modal');
const modalImage = document.getElementById('modal-image');
if (modal && modalImage) {
modalImage.src = imageUrl;
modal.classList.remove('hidden');
modal.classList.add('flex');
}
}
function hideModal() {
const modal = document.getElementById('modal');
if (modal) {
modal.classList.add('hidden');
modal.classList.remove('flex');
}
}
function showInputSelectionModal(promptId) {
state.currentPromptIdForInputSelection = promptId;
const inputModal = document.getElementById('input-selection-modal');
const uploadedContainer = document.getElementById('uploaded-modal-container');
const galleryContainer = document.getElementById('gallery-modal-container');
uploadedContainer.innerHTML = '';
state.uploadedImages.forEach(imgUrl => {
const img = document.createElement('img');
img.src = imgUrl;
img.className = 'w-24 h-24 object-cover rounded-md cursor-pointer transition-transform duration-200 hover:scale-110';
img.addEventListener('click', () => useSelectedAsInput(imgUrl));
uploadedContainer.appendChild(img);
});
if (state.uploadedImages.length === 0) {
uploadedContainer.innerHTML = '<p class="text-sm text-gray-400">Không có ảnh mẫu đã tải lên.</p>';
}
galleryContainer.innerHTML = '';
state.galleryImages.forEach(imgData => {
const img = document.createElement('img');
img.src = imgData.image;
img.className = 'w-24 h-24 object-cover rounded-md cursor-pointer transition-transform duration-200 hover:scale-110';
img.addEventListener('click', () => useSelectedAsInput(imgData.image));
galleryContainer.appendChild(img);
});
if (state.galleryImages.length === 0) {
galleryContainer.innerHTML = '<p class="text-sm text-gray-400">Không có ảnh đã lưu trong thư viện.</p>';
}
inputModal.classList.remove('hidden');
inputModal.classList.add('flex');
}
function hideInputSelectionModal() {
const inputModal = document.getElementById('input-selection-modal');
inputModal.classList.add('hidden');
inputModal.classList.remove('flex');
state.currentPromptIdForInputSelection = null;
}
function useSelectedAsInput(imageUrl) {
const promptId = state.currentPromptIdForInputSelection;
if (promptId !== null) {
state.promptData[promptId].inputImage = imageUrl;
hideInputSelectionModal();
updateUI();
saveToFirestore();
}
}
window.onload = () => {
initApp();
document.getElementById('file-upload').addEventListener('change', handleFileSelect);
document.getElementById('style-select').addEventListener('change', (event) => {
state.selectedStyle = event.target.value;
showMessage(`Đã thay đổi phong cách thành: ${event.target.options[event.target.selectedIndex].text}`, 'info');
});
document.getElementById('prompt-grid').addEventListener('click', (event) => {
const target = event.target.closest('button');
if (!target) return;
const action = target.dataset.action;
const id = parseInt(target.dataset.id);
if (action === 'generate') {
generateImage(id);
} else if (action === 'delete') {
state.promptData[id].outputImage = null;
saveToFirestore();
updateUI();
} else if (action === 'save-gallery') {
saveImageToGallery(id);
} else if (action === 'select-input') {
showInputSelectionModal(id);
} else if (action === 'auto-prompt') {
generateAutoPrompt(id);
} else if (action === 'save-prompt') {
savePromptToGallery(id);
} else if (action === 'copy-prompt') {
copyToClipboard(state.promptData[id].prompt);
}
});
document.getElementById('prompt-grid').addEventListener('input', (event) => {
const target = event.target;
if (target.tagName === 'TEXTAREA' && target.id.startsWith('prompt-')) {
const id = parseInt(target.dataset.id);
state.promptData[id].prompt = target.value;
}
});
document.getElementById('prompt-gallery-container').addEventListener('click', (event) => {
const target = event.target.closest('button');
if (!target) return;
const action = target.dataset.action;
if (action === 'copy-gallery-prompt') {
const promptText = target.dataset.prompt;
copyToClipboard(promptText);
}
});
document.getElementById('modal-close').addEventListener('click', hideModal);
document.getElementById('modal').addEventListener('click', (e) => {
if (e.target.id === 'modal') {
hideModal();
}
});
document.getElementById('input-selection-modal-close').addEventListener('click', hideInputSelectionModal);
document.getElementById('input-selection-modal').addEventListener('click', (e) => {
if (e.target.id === 'input-selection-modal') {
hideInputSelectionModal();
}
});
document.getElementById('message-box').addEventListener('click', hideMessage);
};
</script>
<style>
body {
font-family: 'Inter', sans-serif;
background-color: #f3f4f6;
}
.container {
max-width: 1200px;
}
</style>
</head>
<body class="bg-gray-100 text-gray-800 p-4 min-h-screen flex items-center justify-center">
<!-- Full-screen Modal for viewing images -->
<div id="modal" class="fixed inset-0 bg-black bg-opacity-80 hidden z-50 justify-center items-center p-4">
<div class="relative max-w-5xl max-h-full">
<button id="modal-close" class="absolute top-4 right-4 text-white text-3xl font-bold p-2 leading-none rounded-full bg-gray-800 bg-opacity-50 hover:bg-opacity-80 transition-colors">×</button>
<img id="modal-image" class="max-w-full max-h-[90vh] object-contain rounded-lg shadow-lg">
</div>
</div>
<!-- Input Selection Modal -->
<div id="input-selection-modal" class="fixed inset-0 bg-black bg-opacity-80 hidden z-50 justify-center items-center p-4">
<div class="bg-white rounded-xl shadow-2xl p-6 w-full max-w-4xl max-h-[90vh] overflow-y-auto relative">
<button id="input-selection-modal-close" class="absolute top-4 right-4 text-gray-500 hover:text-gray-800 transition-colors">×</button>
<h3 class="text-2xl font-bold mb-4">Chọn ảnh đầu vào</h3>
<div class="space-y-4">
<div>
<h4 class="font-semibold text-gray-700 mb-2">Ảnh mẫu đã tải lên</h4>
<div id="uploaded-modal-container" class="flex flex-wrap gap-4 mt-2 border border-dashed border-gray-200 p-2 rounded-lg"></div>
</div>
<div>
<h4 class="font-semibold text-gray-700 mb-2">Thư viện ảnh đã lưu</h4>
<div id="gallery-modal-container" class="flex flex-wrap gap-4 min-h-[50px] border border-dashed border-gray-200 p-2 rounded-lg"></div>
</div>
</div>
</div>
</div>
<div class="container mx-auto p-8 bg-white rounded-xl shadow-2xl space-y-8">
<div id="message-box" class="fixed top-4 right-4 z-50 p-4 rounded-lg shadow-lg transition-all duration-300 transform -translate-y-full opacity-0"></div>
<div class="text-center space-y-2">
<h1 class="text-4xl md:text-5xl font-extrabold text-gray-900">
Studio AI
</h1>
<p class="text-lg text-gray-600">
Tạo hình ảnh với nhân vật nhất quán theo cốt truyện.
</p>
<p id="user-id-display" class="text-sm font-mono text-gray-400 mt-2"></p>
</div>
<div class="border-b-2 border-dashed border-gray-300 pb-6 space-y-4">
<h2 class="text-2xl font-bold text-gray-800">1. Tùy chỉnh chung</h2>
<div class="flex flex-col md:flex-row items-start md:items-center space-y-4 md:space-y-0 md:space-x-4">
<div class="flex items-center space-x-4">
<label for="style-select" class="font-semibold text-gray-700">Phong cách:</label>
<select id="style-select" class="p-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-violet-500">
<option value="default">Giữ nguyên phong cách ảnh gốc</option>
<option value="Anime style">Phong cách Anime</option>
<option value="Cartoon style">Phong cách Hoạt hình</option>
<option value="Oil painting">Tranh sơn dầu</option>
<option value="Watercolor painting">Tranh màu nước</option>
<option value="Pixel art">Nghệ thuật Pixel</option>
<option value="Cyberpunk style">Phong cách Cyberpunk</option>
<option value="Fantasy art">Nghệ thuật viễn tưởng</option>
<option value="Realistic photo">Ảnh chân thực</option>
</select>
</div>
<div class="flex-grow">
<label class="block font-semibold text-gray-700 mb-2">Tải ảnh mẫu:</label>
<label class="block">
<span class="sr-only">Tải lên file</span>
<input type="file" id="file-upload" multiple accept="image/*" class="block w-full text-sm text-gray-500
file:mr-4 file:py-2 file:px-4
file:rounded-full file:border-0
file:text-sm file:font-semibold
file:bg-violet-50 file:text-violet-700
hover:file:bg-violet-100 cursor-pointer"/>
</label>
</div>
</div>
<div id="uploaded-images-preview" class="flex flex-wrap gap-4 mt-4 border border-dashed border-gray-200 p-4 rounded-lg">
<p class="text-sm text-gray-400">Các ảnh bạn tải lên sẽ hiển thị ở đây.</p>
</div>
</div>
<div class="space-y-4">
<h2 class="text-2xl font-bold text-gray-800">2. Nhập lời nhắc & Tạo ảnh</h2>
<div id="prompt-grid" class="grid grid-cols-1 md:grid-cols-2 gap-8">
<!-- Card 1 -->
<div class="bg-white rounded-xl shadow-lg p-6 space-y-4 border border-gray-200">
<label class="block text-gray-700 font-semibold">Prompt 1:</label>
<textarea id="prompt-0" data-id="0" rows="3" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-violet-500 transition-shadow"></textarea>
<h3 class="font-semibold text-gray-700">Ảnh đầu vào</h3>
<div id="input-image-container-0" class="w-full h-40 bg-gray-200 rounded-lg flex items-center justify-center cursor-pointer border border-dashed">
<p class="text-sm text-gray-400">Chọn ảnh đầu vào.</p>
</div>
<button data-id="0" data-action="select-input" class="w-full px-4 py-2 bg-gray-200 text-gray-800 font-semibold rounded-full hover:bg-gray-300 transition-colors">Chọn ảnh từ thư viện</button>
<button id="auto-prompt-btn-0" data-id="0" data-action="auto-prompt" class="auto-prompt-btn w-full px-4 py-2 bg-gray-200 text-gray-800 font-semibold rounded-full hover:bg-gray-300 transition-colors flex items-center justify-center">Tạo Prompt tự động</button>
<h3 class="font-semibold text-gray-700 mt-4">Ảnh đầu ra</h3>
<div id="output-image-container-0" class="w-full h-80 bg-gray-200 rounded-lg overflow-hidden flex items-center justify-center">
<svg class="h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l-4 4m6-6l-4 4m6-6a2 2 0 100 4 2 2 0 000-4z"></path></svg>
</div>
<div class="flex flex-wrap gap-2 justify-end mt-4">
<button id="generate-btn-0" data-id="0" data-action="generate" class="generate-btn px-6 py-2 bg-violet-600 text-white font-semibold rounded-full shadow-md hover:bg-violet-700 transition-colors flex items-center justify-center">Tạo ảnh</button>
<button data-id="0" data-action="delete" class="px-6 py-2 bg-red-500 text-white font-semibold rounded-full shadow-md hover:bg-red-600 transition-colors">Xóa</button>
<button data-id="0" data-action="save-gallery" class="px-6 py-2 bg-blue-500 text-white font-semibold rounded-full shadow-md hover:bg-blue-600 transition-colors">Lưu ảnh</button>
<button data-id="0" data-action="save-prompt" class="px-6 py-2 bg-green-500 text-white font-semibold rounded-full shadow-md hover:bg-green-600 transition-colors">Lưu Prompt</button>
<button data-id="0" data-action="copy-prompt" class="px-6 py-2 bg-yellow-500 text-white font-semibold rounded-full shadow-md hover:bg-yellow-600 transition-colors">Sao chép</button>
</div>
</div>
<!-- Card 2 -->
<div class="bg-white rounded-xl shadow-lg p-6 space-y-4 border border-gray-200">
<label class="block text-gray-700 font-semibold">Prompt 2:</label>
<textarea id="prompt-1" data-id="1" rows="3" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-violet-500 transition-shadow"></textarea>
<h3 class="font-semibold text-gray-700">Ảnh đầu vào</h3>
<div id="input-image-container-1" class="w-full h-40 bg-gray-200 rounded-lg flex items-center justify-center cursor-pointer border border-dashed">
<p class="text-sm text-gray-400">Chọn ảnh đầu vào.</p>
</div>
<button data-id="1" data-action="select-input" class="w-full px-4 py-2 bg-gray-200 text-gray-800 font-semibold rounded-full hover:bg-gray-300 transition-colors">Chọn ảnh từ thư viện</button>
<button id="auto-prompt-btn-1" data-id="1" data-action="auto-prompt" class="auto-prompt-btn w-full px-4 py-2 bg-gray-200 text-gray-800 font-semibold rounded-full hover:bg-gray-300 transition-colors flex items-center justify-center">Tạo Prompt tự động</button>
<h3 class="font-semibold text-gray-700 mt-4">Ảnh đầu ra</h3>
<div id="output-image-container-1" class="w-full h-80 bg-gray-200 rounded-lg overflow-hidden flex items-center justify-center">
<svg class="h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l-4 4m6-6l-4 4m6-6a2 2 0 100 4 2 2 0 000-4z"></path></svg>
</div>
<div class="flex flex-wrap gap-2 justify-end mt-4">
<button id="generate-btn-1" data-id="1" data-action="generate" class="generate-btn px-6 py-2 bg-violet-600 text-white font-semibold rounded-full shadow-md hover:bg-violet-700 transition-colors flex items-center justify-center">Tạo ảnh</button>
<button data-id="1" data-action="delete" class="px-6 py-2 bg-red-500 text-white font-semibold rounded-full shadow-md hover:bg-red-600 transition-colors">Xóa</button>
<button data-id="1" data-action="save-gallery" class="px-6 py-2 bg-blue-500 text-white font-semibold rounded-full shadow-md hover:bg-blue-600 transition-colors">Lưu ảnh</button>
<button data-id="1" data-action="save-prompt" class="px-6 py-2 bg-green-500 text-white font-semibold rounded-full shadow-md hover:bg-green-600 transition-colors">Lưu Prompt</button>
<button data-id="1" data-action="copy-prompt" class="px-6 py-2 bg-yellow-500 text-white font-semibold rounded-full shadow-md hover:bg-yellow-600 transition-colors">Sao chép</button>
</div>
</div>
<!-- Card 3 -->
<div class="bg-white rounded-xl shadow-lg p-6 space-y-4 border border-gray-200">
<label class="block text-gray-700 font-semibold">Prompt 3:</label>
<textarea id="prompt-2" data-id="2" rows="3" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-violet-500 transition-shadow"></textarea>
<h3 class="font-semibold text-gray-700">Ảnh đầu vào</h3>
<div id="input-image-container-2" class="w-full h-40 bg-gray-200 rounded-lg flex items-center justify-center cursor-pointer border border-dashed">
<p class="text-sm text-gray-400">Chọn ảnh đầu vào.</p>
</div>
<button data-id="2" data-action="select-input" class="w-full px-4 py-2 bg-gray-200 text-gray-800 font-semibold rounded-full hover:bg-gray-300 transition-colors">Chọn ảnh từ thư viện</button>
<button id="auto-prompt-btn-2" data-id="2" data-action="auto-prompt" class="auto-prompt-btn w-full px-4 py-2 bg-gray-200 text-gray-800 font-semibold rounded-full hover:bg-gray-300 transition-colors flex items-center justify-center">Tạo Prompt tự động</button>
<h3 class="font-semibold text-gray-700 mt-4">Ảnh đầu ra</h3>
<div id="output-image-container-2" class="w-full h-80 bg-gray-200 rounded-lg overflow-hidden flex items-center justify-center">
<svg class="h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l-4 4m6-6l-4 4m6-6a2 2 0 100 4 2 2 0 000-4z"></path></svg>
</div>
<div class="flex flex-wrap gap-2 justify-end mt-4">
<button id="generate-btn-2" data-id="2" data-action="generate" class="generate-btn px-6 py-2 bg-violet-600 text-white font-semibold rounded-full shadow-md hover:bg-violet-700 transition-colors flex items-center justify-center">Tạo ảnh</button>
<button data-id="2" data-action="delete" class="px-6 py-2 bg-red-500 text-white font-semibold rounded-full shadow-md hover:bg-red-600 transition-colors">Xóa</button>
<button data-id="2" data-action="save-gallery" class="px-6 py-2 bg-blue-500 text-white font-semibold rounded-full shadow-md hover:bg-blue-600 transition-colors">Lưu ảnh</button>
<button data-id="2" data-action="save-prompt" class="px-6 py-2 bg-green-500 text-white font-semibold rounded-full shadow-md hover:bg-green-600 transition-colors">Lưu Prompt</button>
<button data-id="2" data-action="copy-prompt" class="px-6 py-2 bg-yellow-500 text-white font-semibold rounded-full shadow-md hover:bg-yellow-600 transition-colors">Sao chép</button>
</div>
</div>
<!-- Card 4 -->
<div class="bg-white rounded-xl shadow-lg p-6 space-y-4 border border-gray-200">
<label class="block text-gray-700 font-semibold">Prompt 4:</label>
<textarea id="prompt-3" data-id="3" rows="3" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-violet-500 transition-shadow"></textarea>
<h3 class="font-semibold text-gray-700">Ảnh đầu vào</h3>
<div id="input-image-container-3" class="w-full h-40 bg-gray-200 rounded-lg flex items-center justify-center cursor-pointer border border-dashed">
<p class="text-sm text-gray-400">Chọn ảnh đầu vào.</p>
</div>
<button data-id="3" data-action="select-input" class="w-full px-4 py-2 bg-gray-200 text-gray-800 font-semibold rounded-full hover:bg-gray-300 transition-colors">Chọn ảnh từ thư viện</button>
<button id="auto-prompt-btn-3" data-id="3" data-action="auto-prompt" class="auto-prompt-btn w-full px-4 py-2 bg-gray-200 text-gray-800 font-semibold rounded-full hover:bg-gray-300 transition-colors flex items-center justify-center">Tạo Prompt tự động</button>
<h3 class="font-semibold text-gray-700 mt-4">Ảnh đầu ra</h3>
<div id="output-image-container-3" class="w-full h-80 bg-gray-200 rounded-lg overflow-hidden flex items-center justify-center">
<svg class="h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l-4 4m6-6l-4 4m6-6a2 2 0 100 4 2 2 0 000-4z"></path></svg>
</div>
<div class="flex flex-wrap gap-2 justify-end mt-4">
<button id="generate-btn-3" data-id="3" data-action="generate" class="generate-btn px-6 py-2 bg-violet-600 text-white font-semibold rounded-full shadow-md hover:bg-violet-700 transition-colors flex items-center justify-center">Tạo ảnh</button>
<button data-id="3" data-action="delete" class="px-6 py-2 bg-red-500 text-white font-semibold rounded-full shadow-md hover:bg-red-600 transition-colors">Xóa</button>
<button data-id="3" data-action="save-gallery" class="px-6 py-2 bg-blue-500 text-white font-semibold rounded-full shadow-md hover:bg-blue-600 transition-colors">Lưu ảnh</button>
<button data-id="3" data-action="save-prompt" class="px-6 py-2 bg-green-500 text-white font-semibold rounded-full shadow-md hover:bg-green-600 transition-colors">Lưu Prompt</button>
<button data-id="3" data-action="copy-prompt" class="px-6 py-2 bg-yellow-500 text-white font-semibold rounded-full shadow-md hover:bg-yellow-600 transition-colors">Sao chép</button>
</div>
</div>
</div>
</div>
<div class="border-t-2 border-dashed border-gray-300 pt-6 space-y-4">
<h2 class="text-2xl font-bold text-gray-800">3. Thư viện</h2>
<div class="space-y-4">
<h3 class="font-semibold text-gray-700">Thư viện ảnh đã lưu</h3>
<div id="gallery-container" class="flex flex-wrap gap-4 rounded-lg border border-dashed border-gray-200 p-4 min-h-[120px]">
<p class="text-sm text-gray-400">Ảnh đã lưu sẽ hiển thị ở đây.</p>
</div>
</div>
<div class="space-y-4">
<h3 class="font-semibold text-gray-700">Thư viện Prompt đã lưu</h3>
<div id="prompt-gallery-container" class="flex flex-col gap-4 rounded-lg border border-dashed border-gray-200 p-4 min-h-[120px]">
<p class="text-sm text-gray-400">Các prompt đã lưu sẽ hiển thị ở đây.</p>
</div>
</div>
</div>
</div>
</body>
</html> |