Transaltor / image.html
Aichatbot12321's picture
Upload 27 files
84e1dd3 verified
Raw History Blame Contribute Delete
32.2 kB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>AI Pro Suite - Image Translator</title>
<link rel="manifest" href="/manifest.json">
<meta name="theme-color" content="#e0c3fc">
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;800&display=swap" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/localforage/1.10.0/localforage.min.js"></script>
<style>
/* CORE ANIMATED BACKGROUND */
body {
font-family: 'Poppins', sans-serif;
background: linear-gradient(-45deg, #a8edea, #fed6e3, #e0c3fc, #8ec5fc);
background-size: 400% 400%;
animation: gradientBG 15s ease infinite;
color: #2d3436;
margin: 0;
height: 100vh;
overflow: hidden;
}
@keyframes gradientBG { 0% { background-position: 0% 50%; } 50% { background-position: 100% 50%; } 100% { background-position: 0% 50%; } }
/* TOPBAR & SIDEBAR */
.topbar {
display: flex; align-items: center; padding: 15px 20px;
background: rgba(255, 255, 255, 0.4); backdrop-filter: blur(15px);
border-bottom: 1px solid rgba(255,255,255,0.6); position: fixed;
top: 0; left: 0; right: 0; z-index: 100;
}
.menuBtn { font-size: 24px; cursor: pointer; color: #0984e3; margin-right: 15px; }
.appTitle { font-size: 20px; font-weight: 800; color: #0984e3; letter-spacing: 1px; }
.sidebar {
position: fixed; top: 0; left: -300px; width: 260px; height: 100%;
background: rgba(255, 255, 255, 0.85); backdrop-filter: blur(20px);
box-shadow: 5px 0 20px rgba(0,0,0,0.1); z-index: 1000;
transition: left 0.4s cubic-bezier(0.25, 0.8, 0.25, 1);
padding: 20px 10px; display: flex; flex-direction: column; gap: 8px;
}
.sidebar.active { left: 0; }
.sidebar button {
background: transparent; border: none; padding: 12px 15px; text-align: left;
font-size: 15px; font-weight: 600; color: #2d3436; border-radius: 12px; cursor: pointer; transition: 0.3s;
}
.sidebar button:hover, .sidebar button.active { background: rgba(9, 132, 227, 0.1); color: #0984e3; }
.sidebar-close-btn { background: #ffeaa7 !important; color: #d63031 !important; margin-bottom: 20px; }
.overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.3); z-index: 999; display: none; opacity: 0; transition: 0.4s; }
.overlay.active { display: block; opacity: 1; }
/* FIXED LAYOUT */
.chat-page-layout { display: flex; flex-direction: column; height: 100vh; padding-top: 60px; box-sizing: border-box; }
.chat-container {
flex: 1; display: flex; flex-direction: column; max-width: 900px; margin: 0 auto; width: 100%;
background: rgba(255, 255, 255, 0.5); backdrop-filter: blur(25px);
border-radius: 20px 20px 0 0; border: 1px solid rgba(255,255,255,0.7);
box-shadow: 0 10px 40px rgba(0,0,0,0.05); overflow: hidden; position: relative;
}
.chat-scroll-area { flex: 1; overflow-y: auto; padding: 20px; scroll-behavior: smooth; }
/* BUBBLES */
.chat-msg { margin-bottom: 20px; animation: slideUpFade 0.4s ease forwards; opacity: 0; transform: translateY(15px); }
.chat-ai { display: flex; justify-content: flex-start; }
.chat-user { display: flex; justify-content: flex-end; }
.bubble { max-width: 90%; padding: 15px; font-size: 14px; line-height: 1.6; border-radius: 20px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); word-wrap: break-word; }
.chat-ai .bubble { background: rgba(255, 255, 255, 0.95); color: #2d3436; border-bottom-left-radius: 5px; border: 1px solid #fff; }
.chat-user .bubble { background: linear-gradient(135deg, #0984e3, #6c5ce7); color: white; border-bottom-right-radius: 5px; }
@keyframes slideUpFade { to { opacity: 1; transform: translateY(0); } }
/* MOBILE RESPONSIVE INPUT AREA */
.chat-input-area {
flex-shrink: 0; padding: 15px; background: rgba(255, 255, 255, 0.85); backdrop-filter: blur(20px);
border-top: 1px solid rgba(255,255,255,0.8); display: flex; flex-direction: column; gap: 10px;
}
.btn-row { display: flex; flex-wrap: wrap; gap: 10px; width: 100%; }
select, .btn {
font-family: 'Poppins', sans-serif; font-size: 14px; font-weight: 600;
padding: 12px 15px; border-radius: 50px; outline: none; cursor: pointer;
transition: all 0.2s ease; border: 2px solid #74b9ff;
}
select { background: rgba(255,255,255,0.9); color: #0984e3; flex: 1 1 100%; }
.btn { background: #ffffff; color: #0984e3; flex: 1 1 calc(50% - 10px); min-width: 130px; box-shadow: 0 4px 10px rgba(9, 132, 227, 0.1); display: flex; justify-content: center; align-items: center; gap: 6px;}
.btn:hover { background: #74b9ff; color: white; transform: translateY(-2px); box-shadow: 0 6px 15px rgba(9, 132, 227, 0.25); }
.btn.send { background: linear-gradient(135deg, #6c5ce7, #0984e3); color: white; border: none; flex: 1 1 100%; min-width: 100%;}
.btn.send:hover { transform: scale(1.02) translateY(-2px); }
/* MODALS */
.action-sheet {
position: absolute; bottom: -100%; left: 0; right: 0; background: white; border-radius: 20px 20px 0 0;
padding: 20px; box-shadow: 0 -10px 40px rgba(0,0,0,0.2); transition: 0.4s cubic-bezier(0.25, 0.8, 0.25, 1); z-index: 100;
}
.action-sheet.active { bottom: 0; }
.photoViewer { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.95); z-index: 9999; display: none; justify-content: center; align-items: center; flex-direction: column;}
.photoViewer.active { display: flex; }
.photoViewer img { max-width: 95%; max-height: 80vh; border-radius: 12px; object-fit: contain;}
.viewer-controls { position: absolute; top: 20px; right: 20px; display: flex; gap: 15px; z-index: 10000; }
.viewer-btn { background: rgba(255,255,255,0.2); color: white; border: none; border-radius: 50%; width: 45px; height: 45px; font-size: 20px; cursor: pointer; display:flex; justify-content:center; align-items:center; text-decoration:none;}
.typing-dot { width: 10px; height: 10px; border-radius: 50%; display: inline-block; animation: typing 1.4s infinite ease-in-out both; }
.typing-dot:nth-child(1) { background: #0984e3; animation-delay: -0.32s; }
.typing-dot:nth-child(2) { background: #6c5ce7; animation-delay: -0.16s; }
.typing-dot:nth-child(3) { background: #fd79a8; }
@keyframes typing { 0%, 80%, 100% { transform: scale(0); } 40% { transform: scale(1); } }
.highlighted-word { background-color: #ffeaa7; font-weight: bold; padding: 2px 4px; border-radius: 4px; color: #d35400; transition: background 0.2s;}
</style>
</head>
<body>
<div class="overlay" id="overlay" onclick="toggleSidebar()"></div>
<div class="topbar">
<div class="menuBtn" onclick="toggleSidebar()">☰</div>
<div class="appTitle">✨ Image Translator</div>
</div>
<div class="sidebar" id="sidebar" style="overflow-y:auto;">
<button class="sidebar-close-btn" onclick="toggleSidebar()">✖ Close Menu</button>
<button onclick="window.location.href='index.html'">🏠 Dashboard</button>
<button onclick="window.location.href='lens.html'">✨ Lens Studio</button>
<button onclick="window.location.href='books.html'">📚 Book Deep Study</button>
<button onclick="window.location.href='maths.html'">🧮 Math Solver</button>
<button onclick="window.location.href='search.html'">🔎 Deep Search</button>
<button onclick="window.location.href='downloader.html'">📥 Video Downloader</button>
<button onclick="window.location.href='board.html'">📋 Whiteboard</button>
<button onclick="window.location.href='clone.html'">📑 Website Cloner</button>
<button onclick="window.location.href='runhtml.html'">🌐 Write HTML</button>
<button onclick="window.location.href='youtube.html'">▶️ YouTube Search</button>
<button onclick="window.location.href='managequiz.html'">⚙️ Manage Quiz</button>
<button onclick="window.location.href='tutor.html'">👨‍🏫 AI Tutor</button>
<button onclick="window.location.href='quiz.html'">📝 Take a Quiz!</button>
<button onclick="window.location.href='book_quiz.html'">📝 Take a Book Quiz!</button>
<button onclick="window.location.href='tables.html'">🔢 Maths Table</button>
<button onclick="window.location.href='coding.html'">💻 AI Coding</button>
<button onclick="window.location.href='chess.html'">♟️ Chess AI</button>
<button onclick="window.location.href='translator.html'">🎙️ Text Translator</button>
<button onclick="window.location.href='image.html'" style="border-left: 4px solid var(--primary); color: var(--primary); background: var(--border-light);">🖼️ Image Translator</button>
<button onclick="window.location.href='create.html'">🎨 Image Creator</button>
<button onclick="window.location.href='qa.html'">📚 Document Q&A</button>
<button onclick="window.location.href='history.html'">🕒 History & Downloads</button>
<button onclick="window.location.href='storage.html'">📂 Storage</button>
<button onclick="window.location.href='hub.html'">🛰️ HF Command Center</button>
<button onclick="window.location.href='live.html'">🗣️ Gemini Live</button>
</div>
<div class="chat-page-layout">
<div class="chat-container">
<div class="chat-scroll-area" id="imageScrollArea">
<div id="imageChatHistory">
<div class="chat-msg chat-ai">
<div class="bubble">
📸 <b>Smart Image Translation</b><br>Take a photo or upload an image. I will seamlessly translate the text right onto the image and find the hardest words for you!
</div>
</div>
</div>
</div>
<div class="action-sheet" id="addImgSheet">
<h3 style="margin-top:0; color:#0984e3; text-align:center;">Add a Photo</h3>
<input type="file" id="imageUploadInput" accept="image/*" style="display:none;" onchange="handleLocalImageUpload(event)">
<div style="display:flex; flex-direction:column; gap:10px;">
<button class="btn" onclick="document.getElementById('imageUploadInput').click(); closeActionSheet();" style="width: 100%;">📁 Upload from Gallery</button>
<button class="btn" onclick="localOpenCamera(); closeActionSheet();" style="width: 100%;">📸 Open Camera</button>
<button class="btn" style="border-color:#ff7675; color:#ff7675; width: 100%;" onclick="closeActionSheet()">❌ Cancel</button>
</div>
</div>
<div class="chat-input-area">
<div style="display: flex; align-items: center; gap: 10px; background: rgba(255,255,255,0.7); padding: 10px; border-radius: 15px; border: 1px solid rgba(9, 132, 227, 0.2);">
<span style="font-weight: 600; color: #636e72; padding-left: 5px; font-size: 13px;">To:</span>
<select id="chatTargetLang" style="border: none; background: transparent; padding: 5px;">
<option value="English">English</option>
<option value="Hindi" selected>Hindi (हिंदी)</option>
<option value="Sanskrit">Sanskrit (संस्कृतम्)</option>
<option disabled>──────────</option>
<option value="French">French</option>
<option value="Spanish">Spanish</option>
<option value="German">German</option>
<option value="Japanese">Japanese</option>
<option value="Arabic">Arabic</option>
<option value="Bengali">Bengali</option>
<option value="Portuguese">Portuguese</option>
<option value="Russian">Russian</option>
<option value="Urdu">Urdu</option>
<option value="Korean">Korean</option>
<option value="Italian">Italian</option>
<option value="Turkish">Turkish</option>
<option value="Tamil">Tamil</option>
<option value="Telugu">Telugu</option>
<option value="Marathi">Marathi</option>
<option value="Gujarati">Gujarati</option>
<option value="Punjabi">Punjabi</option>
</select>
</div>
<div id="imagePreviewContainer" style="display: none; justify-content: center; padding: 5px;"></div>
<div class="btn-row">
<button class="btn" onclick="document.getElementById('addImgSheet').classList.add('active');">📸 Add Image</button>
<button class="btn send" onclick="executeLocalImageTransFlow()">✨ Translate Now</button>
</div>
</div>
</div>
</div>
<div id="cameraModal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; z-index:999999; background:#000; flex-direction:column;">
<video id="cameraVideo" autoplay playsinline style="width:100%; height:100%; object-fit:cover;"></video>
<div style="position:absolute; top:30px; right:20px; z-index:1000000; display:flex; gap:15px;">
<button id="toggleFlashBtn" onclick="localToggleFlash()" style="background:rgba(255,255,255,0.2); color:white; border:none; border-radius:50%; width:50px; height:50px; font-size:24px; cursor:pointer;">⚡</button>
<button onclick="localSwitchCamera()" style="background:rgba(255,255,255,0.2); color:white; border:none; border-radius:50%; width:50px; height:50px; font-size:24px; cursor:pointer;">🔄</button>
<button onclick="localCloseCamera()" style="background:#ff7675; color:white; border:none; border-radius:50%; width:50px; height:50px; font-size:20px; cursor:pointer;">❌</button>
</div>
<div style="position:absolute; bottom:40px; left:0; width:100%; display:flex; justify-content:center; align-items:center; z-index:1000000;">
<div onclick="localCapturePhoto()" style="width:80px; height:80px; background:white; border-radius:50%; border:6px solid #b2bec3; cursor:pointer; box-shadow:0 0 20px rgba(255,255,255,0.5);"></div>
</div>
<canvas id="captureCanvas" style="display:none;"></canvas>
</div>
<div class="photoViewer" id="photoViewer">
<div class="viewer-controls">
<a id="downloadViewerBtn" download="image.png" class="viewer-btn">💾</a>
<button class="viewer-btn" onclick="document.getElementById('photoViewer').classList.remove('active')">✕</button>
</div>
<img id="previewImage">
</div>
<script>
function toggleSidebar() {
document.getElementById('sidebar').classList.toggle('active');
document.getElementById('overlay').classList.toggle('active');
}
function closeActionSheet() {
document.getElementById('addImgSheet').classList.remove('active');
}
// HISTORY LOGIC
document.addEventListener("DOMContentLoaded", async () => {
const history = await localforage.getItem('imgTranslationHistory') || [];
const c = document.getElementById("imageChatHistory");
history.forEach(htmlBlock => {
c.insertAdjacentHTML('beforeend', htmlBlock);
});
setTimeout(() => {
const scrollArea = document.getElementById("imageScrollArea");
scrollArea.scrollTop = scrollArea.scrollHeight;
}, 300);
});
async function saveToHistory(htmlBlock) {
let history = await localforage.getItem('imgTranslationHistory') || [];
history.push(htmlBlock);
if(history.length > 20) history.shift();
await localforage.setItem('imgTranslationHistory', history);
}
function openViewer(src) {
document.getElementById('previewImage').src = src;
document.getElementById('downloadViewerBtn').href = src;
document.getElementById('photoViewer').classList.add('active');
}
// CAMERA LOGIC
let localStream = null;
let localFacing = "environment";
let localFlashOn = false;
window.localOpenCamera = async function() {
const mod = document.getElementById("cameraModal");
mod.style.display = "flex";
try {
if(localStream) localStream.getTracks().forEach(t => t.stop());
localStream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: localFacing, width: {ideal: 1920}, height: {ideal: 1080} } });
const videoEl = document.getElementById("cameraVideo");
videoEl.srcObject = localStream;
const track = localStream.getVideoTracks()[0];
setTimeout(async () => {
try {
const cap = track.getCapabilities();
if (cap.torch && localFacing === "environment") {
localFlashOn = true;
await track.applyConstraints({ advanced: [{ torch: true }] });
}
} catch(e) {}
}, 500);
} catch(e) { alert("Camera Error: " + e.message); }
};
window.localCloseCamera = function() {
document.getElementById("cameraModal").style.display = "none";
if (localStream) {
const track = localStream.getVideoTracks()[0];
try { if (track && track.getCapabilities().torch) track.applyConstraints({ advanced: [{ torch: false }] }); } catch(err) {}
localStream.getTracks().forEach(t => t.stop()); localStream = null;
}
};
window.localSwitchCamera = async function() { localFacing = localFacing === "environment" ? "user" : "environment"; await window.localOpenCamera(); };
window.localToggleFlash = async function() {
if (!localStream) return;
const track = localStream.getVideoTracks()[0];
try {
if (track.getCapabilities().torch) {
localFlashOn = !localFlashOn;
await track.applyConstraints({ advanced: [{ torch: localFlashOn }] });
}
} catch(err) {}
};
window.localCapturePhoto = function() {
const v = document.getElementById("cameraVideo"), c = document.getElementById("captureCanvas");
let w = v.videoWidth, h = v.videoHeight;
c.width = w; c.height = h;
c.getContext("2d").drawImage(v, 0, 0, w, h);
window.localTransImages = [c.toDataURL("image/jpeg", 0.8)];
renderLocalTransImagePreviews();
window.localCloseCamera();
};
// IMAGE UPLOAD
window.localTransImages = [];
window.handleLocalImageUpload = function(event) {
const file = event.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (e) => {
window.localTransImages = [e.target.result];
renderLocalTransImagePreviews();
};
reader.readAsDataURL(file);
};
window.renderLocalTransImagePreviews = function() {
const container = document.getElementById("imagePreviewContainer");
if (window.localTransImages.length === 0) { container.style.display = "none"; return; }
container.style.display = "flex";
container.innerHTML = `<div style="position:relative; width:80px; height:80px; background-image:url(${window.localTransImages[0]}); background-size:cover; border-radius:12px; border:2px solid #0984e3; box-shadow: 0 4px 10px rgba(0,0,0,0.2);"><div onclick="window.localTransImages=[]; window.renderLocalTransImagePreviews()" style="position:absolute; top:-8px; right:-8px; background:#ff7675; color:white; border-radius:50%; width:24px; height:24px; text-align:center; cursor:pointer; font-size:12px; line-height:24px; box-shadow:0 2px 5px rgba(0,0,0,0.3);">✕</div></div>`;
};
// AUDIO LOGIC
window.playTextWithHighlight = function(containerId, rawText, lang) {
window.speechSynthesis.cancel();
const container = document.getElementById(containerId);
if(!container || !rawText) return;
const words = rawText.split(/\s+/);
container.innerHTML = words.map((w, i) => `<span id="${containerId}_w_${i}">${w}</span>`).join(' ');
const synth = window.speechSynthesis;
const utterance = new SpeechSynthesisUtterance(rawText.replace(/[*#]/g, ''));
const langMap = { 'Sanskrit': 'sa-IN', 'Hindi': 'hi-IN', 'French': 'fr-FR', 'Spanish': 'es-ES', 'German': 'de-DE', 'Japanese': 'ja-JP' };
utterance.lang = langMap[lang] || 'en-US';
utterance.rate = 0.9;
utterance.onboundary = function(event) {
if (event.name === 'word') {
let charCount = 0;
for (let i = 0; i < words.length; i++) {
if (charCount >= event.charIndex) {
container.querySelectorAll('span').forEach(s => s.classList.remove('highlighted-word'));
const target = document.getElementById(`${containerId}_w_${i}`);
if(target) target.classList.add('highlighted-word');
break;
}
charCount += words[i].length + 1;
}
}
};
utterance.onend = function() {
container.querySelectorAll('span').forEach(s => s.classList.remove('highlighted-word'));
};
synth.speak(utterance);
};
window.readImageText = function(text, lang) {
window.speechSynthesis.cancel();
const synth = window.speechSynthesis;
const utterance = new SpeechSynthesisUtterance(text);
const langMap = { 'Sanskrit': 'sa-IN', 'Hindi': 'hi-IN', 'French': 'fr-FR', 'Spanish': 'es-ES', 'German': 'de-DE', 'Japanese': 'ja-JP' };
utterance.lang = langMap[lang] || 'en-US';
synth.speak(utterance);
};
// --- PYTHON ADVANCED CANVAS WRAP & FIT FUNCTIONS ---
function wrapText(ctx, text, maxWidth){
const words = text.split(/\s+/).filter(Boolean);
if(words.length === 0) return [''];
const lines = [];
let current = '';
for(const word of words){
const test = current ? current + ' ' + word : word;
if(ctx.measureText(test).width > maxWidth && current){
lines.push(current);
current = word;
}else{
current = test;
}
}
if(current) lines.push(current);
return lines;
}
function fitText(ctx, text, maxWidth, maxHeight, startFontSize){
let fontSize = Math.max(10, Math.floor(startFontSize));
const minFontSize = 8;
while(fontSize > minFontSize){
ctx.font = `600 ${fontSize}px Arial, sans-serif`;
const lines = wrapText(ctx, text, maxWidth);
const totalHeight = lines.length * fontSize * 1.18;
const widest = Math.max(...lines.map(l => ctx.measureText(l).width));
if(totalHeight <= maxHeight * 1.3 && widest <= maxWidth){
return { fontSize, lines };
}
fontSize -= 1;
}
ctx.font = `600 ${minFontSize}px Arial, sans-serif`;
return { fontSize: minFontSize, lines: wrapText(ctx, text, maxWidth) };
}
// MAIN EXECUTION (Using Python Backend's /analyze logic)
window.executeLocalImageTransFlow = async function() {
if (window.localTransImages.length === 0) return alert("Please add an image first!");
const targetLang = document.getElementById("chatTargetLang").value;
const c = document.getElementById("imageChatHistory");
const scrollArea = document.getElementById("imageScrollArea");
let originalImgSrc = window.localTransImages[0];
let userBlock = `<div class="chat-msg chat-user"><div class="bubble"><img src="${originalImgSrc}" onclick="openViewer(this.src)" style="width:120px; border-radius:8px; border:2px solid rgba(255,255,255,0.5); cursor:pointer;"><br><div style="margin-top:5px; font-size:13px;">Translate to <b>${targetLang}</b></div></div></div>`;
c.insertAdjacentHTML('beforeend', userBlock);
const lId = "loading_" + Date.now();
c.insertAdjacentHTML('beforeend', `<div class="chat-msg chat-ai" id="${lId}"><div class="bubble" style="background: rgba(255,255,255,0.7);"><div class="typing-dot"></div><div class="typing-dot"></div><div class="typing-dot"></div></div></div>`);
setTimeout(() => scrollArea.scrollTop = scrollArea.scrollHeight, 100);
window.localTransImages = []; renderLocalTransImagePreviews();
try {
// Calling the Python backend endpoint
const nodeResponse = await fetch('/analyze', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ image: originalImgSrc, target_lang: targetLang })
});
const nodeData = await nodeResponse.json();
if(!nodeResponse.ok || nodeData.error) {
throw new Error(nodeData.error || 'The server returned an error.');
}
const blocks = nodeData.text_blocks || [];
if(blocks.length === 0){
throw new Error('No readable text found in this photo.');
}
const img = new Image();
img.onload = async function() {
const canvas = document.createElement('canvas');
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
let fullTranslatedText = "";
let extractedOriginalText = "";
const W = canvas.width, H = canvas.height;
// The Exact Canvas logic from the Python file
blocks.forEach(block => {
fullTranslatedText += block.translated_text + " ";
extractedOriginalText += block.original_text + "\n";
const [ymin, xmin, ymax, xmax] = block.bbox_2d;
const x = (xmin / 1000) * W;
const y = (ymin / 1000) * H;
const w = ((xmax - xmin) / 1000) * W;
const h = ((ymax - ymin) / 1000) * H;
if(w <= 0 || h <= 0) return;
// Paint over original text with sampled background color
ctx.fillStyle = block.background_color_hex || '#ffffff';
const pad = Math.max(2, h * 0.08);
ctx.fillRect(x - pad, y - pad, w + pad * 2, h + pad * 2);
// Fit and draw the translated text using matched color
const maxFont = Math.max(10, h * 0.85);
const fit = fitText(ctx, block.translated_text || '', w, h, maxFont);
ctx.fillStyle = block.text_color_hex || '#000000';
ctx.textBaseline = 'top';
const lineHeight = fit.fontSize * 1.18;
const totalHeight = fit.lines.length * lineHeight;
let ty = y + (h - totalHeight) / 2;
fit.lines.forEach(line => {
const lw = ctx.measureText(line).width;
ctx.fillText(line, x + (w - lw) / 2, ty);
ty += lineHeight;
});
});
const paintedImageUrl = canvas.toDataURL('image/png');
let dictionaryHtml = "";
let rawDictText = "";
// Fetch dictionary based on exactly what was extracted
if(extractedOriginalText.trim()) {
try {
const dictPrompt = `Analyze this text. Extract 3 to 5 difficult words and define them in ${targetLang}. Format words exactly like: **Word** - Meaning. CRITICAL RULE: DO NOT output any math equations, formulas, or numbers. Ignore all math completely. Text:\n${extractedOriginalText}`;
let resObj = await fetch('/api/gemini-text', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ userPrompt: dictPrompt })
}).then(r => r.json());
rawDictText = resObj.text;
let formattedHTML = rawDictText.replace(/\*\*(.*?)\*\*/g, '<b>$1</b>').replace(/\n/g, '<br>');
dictionaryHtml = `
<div style="margin-top:15px; font-weight:700; color:#6c5ce7;">📖 Dictionary & Meanings</div>
<div id="dict_${lId}" style="background:rgba(108, 92, 231, 0.1); padding:10px; border-radius:10px; margin-top:5px; font-size:14px; border:1px solid rgba(108, 92, 231, 0.3);">
${formattedHTML}
</div>
<button class="btn" style="margin-top:10px; width:100%; border-radius:10px;" onclick="playTextWithHighlight('dict_${lId}', \`${rawDictText.replace(/[`$*#]/g, '').replace(/\n/g, ' ')}\`, '${targetLang}')">🔊 Highlight & Listen</button>
`;
} catch(e) {}
}
let finalHtmlContent = `
<div style="font-weight:700; color:#0984e3; margin-bottom:10px;">✨ Painted Translation:</div>
<div style="position:relative;">
<img src="${paintedImageUrl}" onclick="openViewer(this.src)" style="width:100%; border-radius:12px; cursor:pointer; box-shadow: 0 4px 15px rgba(0,0,0,0.1);">
<button onclick="readImageText(\`${fullTranslatedText.replace(/[`$*#]/g, '')}\`, '${targetLang}')" style="position:absolute; top:10px; right:10px; background:rgba(255,255,255,0.9); border:none; padding:8px 12px; border-radius:20px; font-weight:bold; cursor:pointer; box-shadow:0 2px 10px rgba(0,0,0,0.3); color:#0984e3;">🔊 Read Image</button>
</div>
${dictionaryHtml}
`;
let fullAiBlock = `<div class="chat-msg chat-ai"><div class="bubble">${finalHtmlContent}</div></div>`;
const loader = document.getElementById(lId);
loader.insertAdjacentHTML('afterend', fullAiBlock);
loader.remove();
setTimeout(() => scrollArea.scrollTop = scrollArea.scrollHeight, 100);
saveToHistory(userBlock);
saveToHistory(fullAiBlock);
};
img.src = originalImgSrc;
} catch(e) {
document.getElementById(lId).querySelector('.bubble').innerHTML = `❌ Error: ${e.message}`;
}
};
</script>
</body>
</html>