imageocr / index.html
sarangg's picture
Switch to Google Vision only - remove CLIP/transformers/torch
3004157
Raw History Blame Contribute Delete
23.3 kB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image & PDF OCR + Vision AI</title>
<style>
:root {
--primary: #8b5cf6;
--primary-hover: #7c3aed;
--bg-color: #0f172a;
--card-bg: #1e293b;
--text-color: #f8fafc;
--border-color: #334155;
--error-color: #ef4444;
--success-color: #10b981;
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
}
html,
body {
background-color: #0f172a;
color: #f8fafc;
}
body {
background-color: var(--bg-color);
color: var(--text-color);
display: flex;
justify-content: center;
align-items: flex-start;
min-height: 100vh;
padding: 2rem;
background-image: radial-gradient(circle at 15% 50%, rgba(139, 92, 246, 0.15), transparent 25%),
radial-gradient(circle at 85% 30%, rgba(56, 189, 248, 0.15), transparent 25%);
}
.container {
background-color: var(--card-bg);
border-radius: 1.5rem;
padding: 2.5rem;
width: 100%;
max-width: 620px;
box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);
border: 1px solid rgba(255, 255, 255, 0.05);
}
h1 {
text-align: center;
font-size: 1.8rem;
margin-bottom: 1.5rem;
background: linear-gradient(to right, #a855f7, #3b82f6);
-webkit-background-clip: text;
background-clip: text;
-webkit-text-fill-color: transparent;
}
/* Tabs */
.tabs {
display: flex;
gap: 0.5rem;
margin-bottom: 1.5rem;
background: #0f172a;
border-radius: 0.75rem;
padding: 0.25rem;
}
.tab-btn {
flex: 1;
padding: 0.6rem;
border: none;
border-radius: 0.5rem;
background: transparent;
color: #94a3b8;
font-size: 0.9rem;
font-weight: 600;
cursor: pointer;
transition: all 0.2s;
}
.tab-btn.active {
background: linear-gradient(135deg, var(--primary), #3b82f6);
color: white;
}
.tab-panel {
display: none;
}
.tab-panel.active {
display: block;
}
/* Shared fields */
.form-group {
margin-bottom: 1.25rem;
}
label {
display: block;
margin-bottom: 0.4rem;
font-size: 0.85rem;
font-weight: 500;
color: #cbd5e1;
}
input[type="text"],
input[type="password"] {
width: 100%;
padding: 0.75rem 1rem;
border-radius: 0.75rem;
border: 1px solid var(--border-color);
background-color: #0f172a;
color: var(--text-color);
font-size: 0.95rem;
transition: border-color 0.2s, box-shadow 0.2s;
}
input[type="text"]:focus,
input[type="password"]:focus {
outline: none;
border-color: var(--primary);
box-shadow: 0 0 0 3px rgba(139, 92, 246, 0.25);
}
.input-with-button {
display: flex;
gap: 0.5rem;
}
.file-drop-area {
position: relative;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
width: 100%;
padding: 2.5rem 2rem;
border: 2px dashed var(--border-color);
border-radius: 1rem;
transition: 0.2s;
background-color: rgba(15, 23, 42, 0.5);
cursor: pointer;
text-align: center;
}
.file-drop-area:hover,
.file-drop-area.dragover {
border-color: var(--primary);
background-color: rgba(139, 92, 246, 0.05);
}
.file-msg {
font-size: 0.95rem;
color: #94a3b8;
pointer-events: none;
}
.file-input {
position: absolute;
left: 0;
top: 0;
height: 100%;
width: 100%;
cursor: pointer;
opacity: 0;
}
.preview-container {
display: none;
margin-top: 1rem;
border-radius: 0.75rem;
overflow: hidden;
border: 1px solid var(--border-color);
text-align: center;
background-color: #000;
}
.preview-image {
max-width: 100%;
max-height: 200px;
object-fit: contain;
display: block;
margin: 0 auto;
}
button.primary-btn {
width: 100%;
padding: 0.9rem;
border: none;
border-radius: 0.75rem;
background: linear-gradient(135deg, var(--primary), #3b82f6);
color: white;
font-size: 1rem;
font-weight: 600;
cursor: pointer;
transition: transform 0.1s, box-shadow 0.2s;
margin-top: 0.75rem;
}
button.primary-btn:hover {
box-shadow: 0 10px 15px -3px rgba(139, 92, 246, 0.4);
}
button.primary-btn:active {
transform: scale(0.98);
}
button.primary-btn:disabled {
opacity: 0.7;
cursor: not-allowed;
transform: none;
}
.spinner {
display: none;
width: 20px;
height: 20px;
border: 3px solid rgba(255, 255, 255, 0.3);
border-radius: 50%;
border-top-color: white;
animation: spin 1s ease-in-out infinite;
margin: 0 auto;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
.status-msg {
margin-top: 0.75rem;
text-align: center;
font-size: 0.85rem;
display: none;
}
.status-error {
color: var(--error-color);
}
.status-success {
color: var(--success-color);
}
.result-container {
display: none;
margin-top: 1.5rem;
animation: fadeIn 0.5s;
}
@keyframes fadeIn {
from {
opacity: 0;
transform: translateY(10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.result-title {
font-size: 1rem;
margin-bottom: 0.6rem;
color: #94a3b8;
display: flex;
justify-content: space-between;
align-items: center;
}
.result-box {
background-color: #0f172a;
border: 1px solid var(--border-color);
border-radius: 0.75rem;
padding: 1.25rem;
min-height: 80px;
white-space: pre-wrap;
font-family: 'Courier New', Courier, monospace;
color: #e2e8f0;
line-height: 1.5;
max-height: 280px;
overflow-y: auto;
}
.copy-btn {
background: var(--card-bg);
border: 1px solid var(--border-color);
padding: 0.25rem 0.75rem;
font-size: 0.8rem;
border-radius: 0.5rem;
color: var(--text-color);
box-shadow: none;
width: auto;
margin: 0;
cursor: pointer;
}
.copy-btn:hover {
background-color: #334155;
}
.inline-btn {
margin-top: 0;
padding: 0 1.25rem;
}
/* Classification result tags */
.label-tags {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
margin-top: 0.75rem;
}
.label-tag {
padding: 0.3rem 0.75rem;
border-radius: 9999px;
font-size: 0.8rem;
font-weight: 600;
}
.label-tag:nth-child(1) {
background: rgba(139, 92, 246, 0.25);
color: #c4b5fd;
border: 1px solid rgba(139, 92, 246, 0.4);
}
.label-tag:nth-child(n+2) {
background: rgba(51, 65, 85, 0.5);
color: #94a3b8;
border: 1px solid var(--border-color);
}
.source-badge {
font-size: 0.75rem;
padding: 0.2rem 0.6rem;
border-radius: 9999px;
font-weight: 600;
}
.badge-google {
background: rgba(16, 185, 129, 0.15);
color: #34d399;
border: 1px solid rgba(16, 185, 129, 0.3);
}
.badge-clip {
background: rgba(59, 130, 246, 0.15);
color: #60a5fa;
border: 1px solid rgba(59, 130, 246, 0.3);
}
.category-display {
font-size: 1.4rem;
font-weight: 700;
color: #fff;
margin-bottom: 0.5rem;
}
</style>
</head>
<body>
<div class="container">
<h1>πŸ” OCR & Vision AI</h1>
<!-- Tabs -->
<div class="tabs">
<button class="tab-btn active" id="tabOcr" onclick="switchTab('ocr')">πŸ“„ Extract Text (OCR)</button>
<button class="tab-btn" id="tabVision" onclick="switchTab('vision')">πŸ›οΈ Identify Product</button>
</div>
<!-- Shared: API URL + Key -->
<div class="form-group">
<label for="apiUrl">API URL Base</label>
<input type="text" id="apiUrl" placeholder="https://yourapp.hf.space">
</div>
<div class="form-group">
<label for="apiKey">API Key</label>
<div class="input-with-button">
<input type="password" id="apiKey" value="xkLm9Qz4BvWtUa2Nf8PjX1"
placeholder="Enter your secret API key">
<button type="button" class="copy-btn inline-btn" id="copyApiKeyBtn">Copy</button>
</div>
</div>
<!-- ───── OCR TAB ───── -->
<div class="tab-panel active" id="panelOcr">
<div class="form-group">
<label>Upload Image or PDF</label>
<div class="file-drop-area" id="dropAreaOcr">
<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 24 24" fill="none"
stroke="#94a3b8" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
style="margin-bottom:0.75rem">
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
<polyline points="17 8 12 3 7 8" />
<line x1="12" y1="3" x2="12" y2="15" />
</svg>
<span class="file-msg">Drag & drop or click β€” Image or PDF</span>
<input class="file-input" type="file" id="fileInputOcr" accept="image/*,.pdf">
</div>
<div class="preview-container" id="previewOcr"></div>
</div>
<button class="primary-btn" id="submitOcr">
<span id="btnTextOcr">Extract Text</span>
<div class="spinner" id="spinnerOcr"></div>
</button>
<div id="statusOcr" class="status-msg"></div>
<div class="result-container" id="resultOcr">
<div class="result-title">
<span>Extracted Text</span>
<button class="copy-btn" id="copyOcrBtn">Copy</button>
</div>
<div class="result-box" id="resultBoxOcr"></div>
</div>
</div>
<!-- ───── VISION TAB ───── -->
<div class="tab-panel" id="panelVision">
<div class="form-group">
<label>Upload Product Image</label>
<div class="file-drop-area" id="dropAreaVision">
<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 24 24" fill="none"
stroke="#94a3b8" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
style="margin-bottom:0.75rem">
<rect x="3" y="3" width="18" height="18" rx="2" />
<circle cx="8.5" cy="8.5" r="1.5" />
<polyline points="21 15 16 10 5 21" />
</svg>
<span class="file-msg">Drag & drop or click β€” Image only</span>
<input class="file-input" type="file" id="fileInputVision" accept="image/*">
</div>
<div class="preview-container" id="previewVision"></div>
</div>
<button class="primary-btn" id="submitVision">
<span id="btnTextVision">Identify Product</span>
<div class="spinner" id="spinnerVision"></div>
</button>
<div id="statusVision" class="status-msg"></div>
<div class="result-container" id="resultVision">
<div class="result-title">
<span>Result</span>
<span id="sourceBadge" class="source-badge"></span>
</div>
<div class="category-display" id="categoryDisplay"></div>
<div class="label-tags" id="labelTags"></div>
</div>
</div>
</div>
<script>
// ── Tab switching ─────────────────────────────────────────────────────────
function switchTab(tab) {
document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
document.getElementById('tab' + (tab === 'ocr' ? 'Ocr' : 'Vision')).classList.add('active');
document.getElementById('panel' + (tab === 'ocr' ? 'Ocr' : 'Vision')).classList.add('active');
}
// ── Auto-detect API base URL ──────────────────────────────────────────────
const apiUrlInput = document.getElementById('apiUrl');
const host = window.location.hostname;
apiUrlInput.value = (host === 'localhost' || host === '127.0.0.1')
? 'http://localhost:4002'
: window.location.protocol + '//' + window.location.host;
// ── Copy API Key ──────────────────────────────────────────────────────────
document.getElementById('copyApiKeyBtn').addEventListener('click', () => {
navigator.clipboard.writeText(document.getElementById('apiKey').value).then(() => {
const btn = document.getElementById('copyApiKeyBtn');
btn.textContent = 'Copied!';
setTimeout(() => btn.textContent = 'Copy', 2000);
});
});
// ── Generic file drop setup ───────────────────────────────────────────────
function setupDrop(dropAreaId, fileInputId, previewId, acceptPdf = false) {
const dropArea = document.getElementById(dropAreaId);
const fileInput = document.getElementById(fileInputId);
const preview = document.getElementById(previewId);
let selectedFile = null;
['dragenter', 'dragover', 'dragleave', 'drop'].forEach(ev => dropArea.addEventListener(ev, e => { e.preventDefault(); e.stopPropagation(); }));
['dragenter', 'dragover'].forEach(ev => dropArea.addEventListener(ev, () => dropArea.classList.add('dragover')));
['dragleave', 'drop'].forEach(ev => dropArea.addEventListener(ev, () => dropArea.classList.remove('dragover')));
dropArea.addEventListener('drop', e => handleFiles(e.dataTransfer.files));
fileInput.addEventListener('change', function () { handleFiles(this.files); });
function handleFiles(files) {
if (!files.length) return;
selectedFile = files[0];
const isPdf = selectedFile.type === 'application/pdf' || selectedFile.name.endsWith('.pdf');
const isImg = selectedFile.type.startsWith('image/');
if (!isImg && !(acceptPdf && isPdf)) {
alert('Please select a valid file.');
selectedFile = null; return;
}
if (isPdf) {
preview.innerHTML = `<div style="padding:1.2rem;text-align:center;color:#94a3b8">πŸ“„ <strong style="color:#e2e8f0">${selectedFile.name}</strong><br><small>${(selectedFile.size / 1024).toFixed(1)} KB</small></div>`;
} else {
const fr = new FileReader();
fr.onloadend = () => { preview.innerHTML = `<img class="preview-image" src="${fr.result}" alt="preview">`; };
fr.readAsDataURL(selectedFile);
}
preview.style.display = 'block';
dropArea.style.display = 'none';
}
preview.addEventListener('dblclick', () => { fileInput.click(); dropArea.style.display = ''; preview.style.display = 'none'; });
return { getFile: () => selectedFile };
}
const ocrDrop = setupDrop('dropAreaOcr', 'fileInputOcr', 'previewOcr', true);
const visionDrop = setupDrop('dropAreaVision', 'fileInputVision', 'previewVision', false);
function setLoading(btnTextId, spinnerId, btnId, loading) {
document.getElementById(btnTextId).style.display = loading ? 'none' : 'block';
document.getElementById(spinnerId).style.display = loading ? 'block' : 'none';
document.getElementById(btnId).disabled = loading;
}
function showStatus(id, msg, ok) {
const el = document.getElementById(id);
el.textContent = msg;
el.className = 'status-msg ' + (ok ? 'status-success' : 'status-error');
el.style.display = 'block';
}
// ── OCR submit ────────────────────────────────────────────────────────────
document.getElementById('submitOcr').addEventListener('click', async () => {
const file = ocrDrop.getFile();
if (!file) return showStatus('statusOcr', 'Please select a file.', false);
const apiUrl = document.getElementById('apiUrl').value.trim();
const apiKey = document.getElementById('apiKey').value.trim();
setLoading('btnTextOcr', 'spinnerOcr', 'submitOcr', true);
document.getElementById('statusOcr').style.display = 'none';
document.getElementById('resultOcr').style.display = 'none';
const fd = new FormData(); fd.append('file', file);
try {
const res = await fetch(apiUrl + '/ocr', { method: 'POST', headers: { 'x-api-key': apiKey }, body: fd });
const data = await res.json();
if (res.ok) {
showStatus('statusOcr', 'Text extracted successfully!', true);
document.getElementById('resultBoxOcr').textContent = data.extracted_text || '(No text found)';
document.getElementById('resultOcr').style.display = 'block';
} else {
showStatus('statusOcr', 'Error: ' + (data.detail || 'Unknown error'), false);
}
} catch (e) { showStatus('statusOcr', 'Network Error: ' + e.message, false); }
finally { setLoading('btnTextOcr', 'spinnerOcr', 'submitOcr', false); }
});
document.getElementById('copyOcrBtn').addEventListener('click', () => {
navigator.clipboard.writeText(document.getElementById('resultBoxOcr').textContent).then(() => {
const btn = document.getElementById('copyOcrBtn');
btn.textContent = 'Copied!';
setTimeout(() => btn.textContent = 'Copy', 2000);
});
});
// ── Vision submit ─────────────────────────────────────────────────────────
document.getElementById('submitVision').addEventListener('click', async () => {
const file = visionDrop.getFile();
if (!file) return showStatus('statusVision', 'Please select an image.', false);
const apiUrl = document.getElementById('apiUrl').value.trim();
const apiKey = document.getElementById('apiKey').value.trim();
setLoading('btnTextVision', 'spinnerVision', 'submitVision', true);
document.getElementById('statusVision').style.display = 'none';
document.getElementById('resultVision').style.display = 'none';
const fd = new FormData(); fd.append('file', file);
try {
const res = await fetch(apiUrl + '/classify', { method: 'POST', headers: { 'x-api-key': apiKey }, body: fd });
const data = await res.json();
if (res.ok) {
showStatus('statusVision', 'Product identified!', true);
// Category
document.getElementById('categoryDisplay').textContent = '🏷️ ' + data.category;
// Source badge
const badge = document.getElementById('sourceBadge');
badge.textContent = '⚑ Google Vision';
badge.className = 'source-badge badge-google';
// Label tags
const tagsEl = document.getElementById('labelTags');
tagsEl.innerHTML = data.labels.map(l => `<span class="label-tag">${l}</span>`).join('');
document.getElementById('resultVision').style.display = 'block';
} else {
showStatus('statusVision', 'Error: ' + (data.detail || 'Unknown error'), false);
}
} catch (e) { showStatus('statusVision', 'Network Error: ' + e.message, false); }
finally { setLoading('btnTextVision', 'spinnerVision', 'submitVision', false); }
});
</script>
</body>
</html>