مبادرة ض

test-ocr

document.getElementById('uploadForm').addEventListener('submit', async function(event) {
  event.preventDefault();

  const fileInput = document.getElementById('imageFile');
  const file = fileInput.files[0];
  if (!file) {
    alert('Please select an image file.');
    return;
  }

  const reader = new FileReader();
  reader.onload = async function() {
    const imageData = reader.result.split(',')[1];
    const endpoint = 'https://instance-ai-vision.cognitiveservices.azure.com/';
    const subscriptionKey = 'a1072cf7830c4ff38a9433b13cf89434';

    try {
      const response = await fetch(`${endpoint}/vision/v3.2/read/analyze`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/octet-stream',
          'Ocp-Apim-Subscription-Key': subscriptionKey
        },
        body: new Blob([new Uint8Array(atob(imageData).split("").map(c => c.charCodeAt(0)))])
      });

      if (response.ok) {
        const operationLocation = response.headers.get('Operation-Location');
        console.log('Operation Location:', operationLocation);
        const result = await getOcrResult(operationLocation, subscriptionKey);
        document.getElementById('result').innerText = result;
      } else {
        const errorText = await response.text();
        console.error('Error in OCR process:', errorText);
        alert('Error in OCR process');
      }
    } catch (error) {
      console.error('Error:', error);
      alert('An error occurred. Please check the console for details.');
    }
  };

  reader.readAsDataURL(file);
});

async function getOcrResult(operationLocation, subscriptionKey) {
  let result = '';
  try {
    while (!result) {
      const response = await fetch(operationLocation, {
        headers: {
          'Ocp-Apim-Subscription-Key': subscriptionKey
        }
      });
      const data = await response.json();
      console.log('OCR Result:', data);

      if (data.status === 'succeeded') {
        result = data.analyzeResult.readResults.map(page => page.lines.map(line => line.text).join('\n')).join('\n\n');
      } else if (data.status === 'failed') {
        throw new Error('OCR failed');
      }
      await new Promise(resolve => setTimeout(resolve, 1000)); // Wait for 1 second before retrying
    }
  } catch (error) {
    console.error('Error fetching OCR result:', error);
    alert('Failed to fetch OCR result. Please try again.');
  }
  return result;
}

اترك تعليقاً

لن يتم نشر عنوان بريدك الإلكتروني. الحقول الإلزامية مشار إليها بـ *