modified logic in ocr
This commit is contained in:
@@ -746,352 +746,6 @@ function cameraCapture() {
|
||||
|
||||
|
||||
<script>
|
||||
// function cameraCapture() {
|
||||
// return {
|
||||
// stream: null,
|
||||
// currentFacingMode: 'user',
|
||||
// textDetectionInterval: null,
|
||||
// capturedPhoto: null, // store captured image
|
||||
// serialNumbers: [],
|
||||
// ocrWorker: null,
|
||||
// isWorkerReady: false,
|
||||
|
||||
// async initCamera() {
|
||||
// try {
|
||||
|
||||
// await this.initWorker();
|
||||
|
||||
// if (this.stream) this.stream.getTracks().forEach(track => track.stop());
|
||||
|
||||
// const video = this.$refs.video;
|
||||
// this.stream = await navigator.mediaDevices.getUserMedia({
|
||||
// video: { facingMode: this.currentFacingMode }
|
||||
// });
|
||||
|
||||
// video.srcObject = this.stream;
|
||||
// await new Promise(resolve => video.onloadedmetadata = resolve);
|
||||
// video.play();
|
||||
|
||||
// // Overlay size matches video
|
||||
// const overlay = this.$refs.overlay;
|
||||
// overlay.width = video.videoWidth;
|
||||
// overlay.height = video.videoHeight;
|
||||
|
||||
// this.startDetection();
|
||||
// } catch (err) {
|
||||
// console.error("Camera error:", err);
|
||||
// alert("Camera error:\n" + (err.message || err));
|
||||
// this.stopDetection();
|
||||
// }
|
||||
// },
|
||||
|
||||
// async initWorker() {
|
||||
// if (this.ocrWorker) return;
|
||||
|
||||
// console.log("⏳ Loading OCR worker...");
|
||||
|
||||
// this.ocrWorker = await Tesseract.createWorker({
|
||||
// logger: info => console.log(info.status, info.progress)
|
||||
// });
|
||||
|
||||
// await this.ocrWorker.loadLanguage('eng');
|
||||
// await this.ocrWorker.initialize('eng');
|
||||
// this.isWorkerReady = true;
|
||||
|
||||
// console.log("✅ OCR Worker Ready");
|
||||
// },
|
||||
|
||||
// async switchCamera() {
|
||||
// this.currentFacingMode = this.currentFacingMode === 'user' ? 'environment' : 'user';
|
||||
// await this.initCamera();
|
||||
// },
|
||||
|
||||
// // async capturePhoto() {
|
||||
// // const video = this.$refs.video;
|
||||
// // const canvas = this.$refs.canvas;
|
||||
// // const ctx = canvas.getContext('2d');
|
||||
|
||||
// // canvas.width = video.videoWidth;
|
||||
// // canvas.height = video.videoHeight;
|
||||
// // ctx.drawImage(video, 0, 0);
|
||||
|
||||
// // // const snapshotData = canvas.toDataURL('image/png');
|
||||
// // // this.$refs.hiddenInput.value = snapshotData;
|
||||
// // // this.capturedPhoto = snapshotData; // store for verification
|
||||
// // const snapshotData = canvas.toDataURL('image/png');
|
||||
// // this.$refs.hiddenInput.value = snapshotData;
|
||||
// // this.capturedPhoto = snapshotData;
|
||||
|
||||
// // // Stop camera stream
|
||||
// // if (this.stream) this.stream.getTracks().forEach(track => track.stop());
|
||||
|
||||
// // // snapshot.src = dataUrl;
|
||||
// // // snapshot.classList.remove('hidden');
|
||||
// // // video.classList.add('hidden');
|
||||
// // // const snapshot = this.$refs.snapshot;
|
||||
// // // snapshot.src = snapshotData;
|
||||
// // // snapshot.classList.remove('hidden');
|
||||
// // // video.classList.add('hidden');
|
||||
// // // overlay.classList.add('hidden');
|
||||
// // snapshot.src = dataUrl;
|
||||
// // snapshot.classList.remove('hidden');
|
||||
// // video.classList.add('hidden');
|
||||
|
||||
// // alert("Photo captured!");
|
||||
// // this.stopDetection();
|
||||
// // },
|
||||
|
||||
// async capturePhoto() {
|
||||
// const video = this.$refs.video;
|
||||
// const canvas = this.$refs.canvas;
|
||||
// const overlay = this.$refs.overlay;
|
||||
// const snapshot = this.$refs.snapshot; // ✅ Fix: define snapshot reference
|
||||
// const ctx = canvas.getContext('2d');
|
||||
|
||||
// canvas.width = video.videoWidth;
|
||||
// canvas.height = video.videoHeight;
|
||||
// ctx.drawImage(video, 0, 0);
|
||||
|
||||
// const snapshotData = canvas.toDataURL('image/png'); // ✅ Correct data var
|
||||
// this.$refs.hiddenInput.value = snapshotData;
|
||||
// this.capturedPhoto = snapshotData;
|
||||
|
||||
// // ✅ Stop camera
|
||||
// if (this.stream) this.stream.getTracks().forEach(track => track.stop());
|
||||
|
||||
// // ✅ Hide video + overlay
|
||||
// video.classList.add('hidden');
|
||||
// overlay.classList.add('hidden');
|
||||
|
||||
// // ✅ Show captured image
|
||||
// snapshot.src = snapshotData; // ✅ Correct variable
|
||||
// snapshot.classList.remove('hidden');
|
||||
|
||||
// alert("Photo captured!");
|
||||
// this.stopDetection();
|
||||
// },
|
||||
|
||||
// async verifyPhoto() {
|
||||
// if (!this.capturedPhoto) {
|
||||
// alert("Please capture a photo first!");
|
||||
// return;
|
||||
// }
|
||||
|
||||
// if (!this.isWorkerReady) {
|
||||
// alert("OCR worker not ready yet!");
|
||||
// return;
|
||||
// }
|
||||
|
||||
// try {
|
||||
// const img = new Image();
|
||||
// img.src = this.capturedPhoto;
|
||||
|
||||
// img.onload = async () => {
|
||||
// const canvas = document.createElement('canvas');
|
||||
// canvas.width = img.width;
|
||||
// canvas.height = img.height;
|
||||
// const ctx = canvas.getContext('2d');
|
||||
// ctx.drawImage(img, 0, 0);
|
||||
|
||||
// // const result = await Tesseract.recognize(canvas, 'eng', {
|
||||
// // logger: m => console.log(m)
|
||||
// // });
|
||||
|
||||
// // const result = await Tesseract.recognize(canvas, 'eng', {
|
||||
// // logger: m => console.log(m.status, m.progress)
|
||||
// // });
|
||||
|
||||
// const result = await this.ocrWorker.recognize(img);
|
||||
|
||||
// const detectedText = result.data.text.trim();
|
||||
// // const matches = detectedText.match(/\d+/g) || [];
|
||||
|
||||
// // const serialRegex = /Serial\s*No[:\-]?\s*([A-Za-z0-9]+)/i;
|
||||
// // const match = detectedText.match(serialRegex);
|
||||
|
||||
// // this.serialNumbers = matches.slice(0, 4); // take first 4 serials
|
||||
// const serialWithLabelRegex = /Serial\s*No[:\-]?\s*([A-Za-z0-9]+)/i;
|
||||
// const match = detectedText.match(serialWithLabelRegex);
|
||||
|
||||
// if (match && match[1]) {
|
||||
// //Scenario Found "Serial No"
|
||||
// this.serialNumbers = [match[1].trim()];
|
||||
// console.log("Serial with Label:", this.serialNumbers[0]);
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// //Extract first 4 numbers
|
||||
// const generalNums = detectedText.match(/[A-Za-z0-9]{4,}/g) || [];
|
||||
// this.serialNumbers = generalNums.slice(0, 4);
|
||||
|
||||
// if (this.serialNumbers.length == 0) {
|
||||
// alert("No serial numbers detected!");
|
||||
// return;
|
||||
// }
|
||||
|
||||
// console.log("Serial Numbers List:", this.serialNumbers);
|
||||
// }
|
||||
|
||||
// this.$refs.hiddenInputSerials.value = JSON.stringify(this.serialNumbers);
|
||||
// alert("Serial numbers:\n" + this.$refs.hiddenInputSerials.value);
|
||||
// fetch('/save-serials-to-session', {
|
||||
// method: 'POST',
|
||||
// credentials: 'same-origin',
|
||||
// headers: {
|
||||
// 'Content-Type': 'application/json',
|
||||
// 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
|
||||
// },
|
||||
// body: JSON.stringify({
|
||||
// serial_numbers: this.serialNumbers,
|
||||
// }),
|
||||
// })
|
||||
// .then(response => response.json())
|
||||
// .then(data => {
|
||||
// console.log("✅ Session Updated:", data);
|
||||
// alert("✅ Serial numbers saved to session!");
|
||||
// })
|
||||
// }
|
||||
// } catch (err) {
|
||||
// console.error("OCR verify error:", err);
|
||||
// alert("OCR verify failed:\n" + (err.message || err));
|
||||
// }
|
||||
// },
|
||||
|
||||
|
||||
// data() {
|
||||
// return {
|
||||
// tempCanvas: null,
|
||||
// tempCtx: null,
|
||||
// isDetecting: false,
|
||||
// };
|
||||
// },
|
||||
|
||||
// mounted() {
|
||||
// this.tempCanvas = document.createElement('canvas');
|
||||
// this.tempCtx = this.tempCanvas.getContext('2d');
|
||||
// },
|
||||
|
||||
// async detectText() {
|
||||
// if (this.isDetecting) return;
|
||||
// this.isDetecting = true;
|
||||
|
||||
// const video = this.$refs.video;
|
||||
// const overlay = this.$refs.overlay;
|
||||
// const ctx = overlay.getContext('2d');
|
||||
|
||||
// if (!video.videoWidth) {
|
||||
// this.isDetecting = false;
|
||||
// return;
|
||||
// }
|
||||
|
||||
// // 🔥 Reuse temp canvas (no memory leak)
|
||||
// this.tempCanvas.width = video.videoWidth;
|
||||
// this.tempCanvas.height = video.videoHeight;
|
||||
|
||||
// this.tempCtx.drawImage(video, 0, 0);
|
||||
|
||||
// try {
|
||||
// const result = await Tesseract.recognize(this.tempCanvas, 'eng');
|
||||
// const words = result.data.words;
|
||||
|
||||
// ctx.clearRect(0, 0, overlay.width, overlay.height);
|
||||
// ctx.strokeStyle = 'lime';
|
||||
// ctx.lineWidth = 2;
|
||||
|
||||
// words.forEach(w => {
|
||||
// if (!w.bbox || w.confidence < 50) return;
|
||||
// const { x0, y0, x1, y1 } = w.bbox;
|
||||
// ctx.strokeRect(x0, y0, x1 - x0, y1 - y0);
|
||||
// });
|
||||
|
||||
// } catch (err) {
|
||||
// console.error("Live OCR error:", err);
|
||||
// }
|
||||
|
||||
// this.isDetecting = false;
|
||||
// }
|
||||
|
||||
// // async detectText() {
|
||||
// // const video = this.$refs.video;
|
||||
// // const overlay = this.$refs.overlay;
|
||||
// // const ctx = overlay.getContext('2d');
|
||||
|
||||
// // if (!video.videoWidth) return;
|
||||
|
||||
// // const tempCanvas = document.createElement('canvas');
|
||||
// // tempCanvas.width = video.videoWidth;
|
||||
// // tempCanvas.height = video.videoHeight;
|
||||
// // const tempCtx = tempCanvas.getContext('2d');
|
||||
// // tempCtx.drawImage(video, 0, 0);
|
||||
|
||||
// // try {
|
||||
// // const result = await Tesseract.recognize(tempCanvas, 'eng');
|
||||
// // const words = result.data.words;
|
||||
|
||||
// // ctx.clearRect(0, 0, overlay.width, overlay.height);
|
||||
// // ctx.strokeStyle = 'lime';
|
||||
// // ctx.lineWidth = 2;
|
||||
|
||||
// // words.forEach(w => {
|
||||
// // if (!w.bbox || w.confidence < 50) return;
|
||||
// // const { x0, y0, x1, y1 } = w.bbox;
|
||||
// // ctx.strokeRect(x0, y0, x1 - x0, y1 - y0);
|
||||
// // });
|
||||
// // } catch (err) {
|
||||
// // console.error("Live OCR error:", err);
|
||||
// // }
|
||||
// // },
|
||||
|
||||
// async retakePhoto() {
|
||||
// this.photoTaken = false;
|
||||
// this.$refs.snapshot.classList.add('hidden');
|
||||
// this.$refs.video.classList.remove('hidden');
|
||||
// await this.initCamera();
|
||||
// await new Promise(resolve => {
|
||||
// this.$refs.video.onloadedmetadata = resolve;
|
||||
// });
|
||||
// const video = this.$refs.video;
|
||||
// const overlay = this.$refs.overlay;
|
||||
// overlay.width = video.videoWidth;
|
||||
// overlay.height = video.videoHeight;
|
||||
|
||||
// // Clear old green boxes
|
||||
// const ctx = overlay.getContext('2d');
|
||||
// ctx.clearRect(0, 0, overlay.width, overlay.height);
|
||||
|
||||
// // Make overlay visible if hidden
|
||||
// overlay.classList.remove('hidden');
|
||||
// this.startDetection();
|
||||
// },
|
||||
|
||||
// // startDetection() {
|
||||
// // if (this.textDetectionInterval) clearInterval(this.textDetectionInterval);
|
||||
// // this.textDetectionInterval = setInterval(() => this.detectText(), 1500);
|
||||
// // },
|
||||
|
||||
// startDetection() {
|
||||
// if (this.textDetectionInterval)
|
||||
// clearInterval(this.textDetectionInterval);
|
||||
|
||||
// // Run IMMEDIATELY after retake
|
||||
// this.detectText();
|
||||
|
||||
// // Then keep scanning every 1200ms
|
||||
// this.textDetectionInterval = setInterval(() => {
|
||||
// this.detectText();
|
||||
// }, 1200);
|
||||
// }
|
||||
|
||||
// stopDetection() {
|
||||
// if (this.textDetectionInterval) {
|
||||
// clearInterval(this.textDetectionInterval);
|
||||
// this.textDetectionInterval = null;
|
||||
// console.log("Text detection stopped");
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
|
||||
function cameraCapture() {
|
||||
return {
|
||||
@@ -1214,83 +868,164 @@ function cameraCapture() {
|
||||
},
|
||||
|
||||
|
||||
async verifyPhoto() {
|
||||
if (!this.capturedPhoto) {
|
||||
alert("Please capture a photo first!");
|
||||
return;
|
||||
}
|
||||
// async verifyPhoto() {
|
||||
// if (!this.capturedPhoto) {
|
||||
// alert("Please capture a photo first!");
|
||||
// return;
|
||||
// }
|
||||
|
||||
if (!this.isWorkerReady) {
|
||||
alert("OCR worker not ready yet!");
|
||||
return;
|
||||
}
|
||||
// if (!this.isWorkerReady) {
|
||||
// alert("OCR worker not ready yet!");
|
||||
// return;
|
||||
// }
|
||||
|
||||
try {
|
||||
const img = new Image();
|
||||
img.src = this.capturedPhoto;
|
||||
// try {
|
||||
// const img = new Image();
|
||||
// img.src = this.capturedPhoto;
|
||||
|
||||
img.onload = async () => {
|
||||
// img.onload = async () => {
|
||||
|
||||
// Draw image to a temp canvas for OCR
|
||||
this.tempCanvas.width = img.width;
|
||||
this.tempCanvas.height = img.height;
|
||||
this.tempCtx.drawImage(img, 0, 0);
|
||||
// // Draw image to a temp canvas for OCR
|
||||
// this.tempCanvas.width = img.width;
|
||||
// this.tempCanvas.height = img.height;
|
||||
// this.tempCtx.drawImage(img, 0, 0);
|
||||
|
||||
// OCR using worker
|
||||
const result = await this.ocrWorker.recognize(this.tempCanvas);
|
||||
const detectedText = result.data.text.trim();
|
||||
console.log("Detected OCR Text:", detectedText);
|
||||
// // OCR using worker
|
||||
// const result = await this.ocrWorker.recognize(this.tempCanvas);
|
||||
// const detectedText = result.data.text.trim();
|
||||
// console.log("Detected OCR Text:", detectedText);
|
||||
|
||||
let serials = [];
|
||||
// let serials = [];
|
||||
|
||||
// 1️⃣ Look for pattern “Serial No: ABC123”
|
||||
const serialWithLabelRegex = /Serial\s*No[:\-]?\s*([A-Za-z0-9]+)/i;
|
||||
const match = detectedText.match(serialWithLabelRegex);
|
||||
// // 1️⃣ Look for pattern “Serial No: ABC123”
|
||||
// const serialWithLabelRegex = /Serial\s*No[:\-]?\s*([A-Za-z0-9]+)/i;
|
||||
// const match = detectedText.match(serialWithLabelRegex);
|
||||
|
||||
if (match && match[1]) {
|
||||
serials = [match[1].trim()];
|
||||
console.log("Found labeled serial:", serials[0]);
|
||||
} else {
|
||||
// 2️⃣ No label found → extract 4+ char alphanumeric (first 4 items)
|
||||
const generalNums = detectedText.match(/[A-Za-z0-9]{4,}/g) || [];
|
||||
// if (match && match[1]) {
|
||||
// serials = [match[1].trim()];
|
||||
// console.log("Found labeled serial:", serials[0]);
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// const generalNums = detectedText.match(/[A-Za-z0-9]{4,}/g) || [];
|
||||
|
||||
serials = generalNums.slice(0, 4);
|
||||
// serials = generalNums.slice(0, 4);
|
||||
|
||||
if (serials.length === 0) {
|
||||
alert("No serial numbers detected in the photo!");
|
||||
return;
|
||||
}
|
||||
// if (serials.length == 0) {
|
||||
// alert("No serial numbers detected in the photo!");
|
||||
// return;
|
||||
// }
|
||||
|
||||
console.log("Extracted possible serials:", serials);
|
||||
// console.log("Extracted possible serials:", serials);
|
||||
// }
|
||||
|
||||
// this.serialNumbers = serials;
|
||||
|
||||
// this.$refs.hiddenInputSerials.value = JSON.stringify(this.serialNumbers);
|
||||
|
||||
// // POST to Laravel session
|
||||
// const response = await fetch('/save-serials-to-session', {
|
||||
// method: 'POST',
|
||||
// credentials: 'same-origin',
|
||||
// headers: {
|
||||
// 'Content-Type': 'application/json',
|
||||
// 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
|
||||
// },
|
||||
// body: JSON.stringify({
|
||||
// serial_numbers: this.serialNumbers,
|
||||
// }),
|
||||
// });
|
||||
|
||||
// const data = await response.json();
|
||||
// console.log("Session update result:", data);
|
||||
// alert("✅ Serial numbers saved:\n" + JSON.stringify(this.serialNumbers, null, 2));
|
||||
// };
|
||||
// } catch (err) {
|
||||
// console.error("OCR verify error:", err);
|
||||
// alert("OCR verify failed:\n" + (err.message || err));
|
||||
// }
|
||||
// },
|
||||
|
||||
|
||||
async verifyPhoto() {
|
||||
if (!this.capturedPhoto) {
|
||||
alert("Please capture a photo first!");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.isWorkerReady) {
|
||||
alert("OCR worker not ready yet!");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const img = new Image();
|
||||
img.src = this.capturedPhoto;
|
||||
|
||||
img.onload = async () => {
|
||||
|
||||
// Reuse the same temp canvas (no memory leak)
|
||||
this.tempCanvas.width = img.width;
|
||||
this.tempCanvas.height = img.height;
|
||||
this.tempCtx.drawImage(img, 0, 0);
|
||||
|
||||
// Worker OCR — much faster
|
||||
const result = await this.ocrWorker.recognize(this.tempCanvas);
|
||||
|
||||
const detectedText = result.data.text.trim();
|
||||
console.log("Detected Text:", detectedText);
|
||||
|
||||
// -------------------------------------------------------
|
||||
// SERIAL EXTRACTION LOGIC — SAME AS YOUR ORIGINAL
|
||||
// -------------------------------------------------------
|
||||
const serialWithLabelRegex = /Serial\s*No[:\-]?\s*([A-Za-z0-9]+)/i;
|
||||
const match = detectedText.match(serialWithLabelRegex);
|
||||
|
||||
if (match && match[1]) {
|
||||
// "Serial No: XXXXX"
|
||||
this.serialNumbers = [match[1].trim()];
|
||||
console.log("Serial with Label:", this.serialNumbers[0]);
|
||||
} else {
|
||||
// Extract first 4 alphanumeric sequences of 4+ chars
|
||||
const generalNums = detectedText.match(/[A-Za-z0-9]{4,}/g) || [];
|
||||
this.serialNumbers = generalNums.slice(0, 4);
|
||||
|
||||
if (this.serialNumbers.length === 0) {
|
||||
alert("No serial numbers detected!");
|
||||
return;
|
||||
}
|
||||
|
||||
this.serialNumbers = serials;
|
||||
|
||||
// Save to hidden input for form submit
|
||||
this.$refs.hiddenInputSerials.value = JSON.stringify(this.serialNumbers);
|
||||
|
||||
// POST to Laravel session
|
||||
const response = await fetch('/save-serials-to-session', {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
serial_numbers: this.serialNumbers,
|
||||
}),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
console.log("Session update result:", data);
|
||||
alert("✅ Serial numbers saved:\n" + JSON.stringify(this.serialNumbers, null, 2));
|
||||
};
|
||||
} catch (err) {
|
||||
console.error("OCR verify error:", err);
|
||||
alert("OCR verify failed:\n" + (err.message || err));
|
||||
console.log("Serial Numbers List:", this.serialNumbers);
|
||||
}
|
||||
},
|
||||
|
||||
// Save into hidden input (your original logic)
|
||||
this.$refs.hiddenInputSerials.value = JSON.stringify(this.serialNumbers);
|
||||
|
||||
alert("Serial numbers:\n" + this.$refs.hiddenInputSerials.value);
|
||||
|
||||
fetch('/save-serials-to-session', {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
serial_numbers: this.serialNumbers,
|
||||
}),
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
console.log("Session Updated:", data);
|
||||
alert("✅ Serial numbers saved to session!");
|
||||
});
|
||||
};
|
||||
|
||||
} catch (err) {
|
||||
console.error("OCR verify error:", err);
|
||||
alert("OCR verify failed:\n" + (err.message || err));
|
||||
}
|
||||
}
|
||||
|
||||
startDetection() {
|
||||
if (this.textDetectionInterval) {
|
||||
|
||||
Reference in New Issue
Block a user