File size: 2,521 Bytes
bcf46c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
document.getElementById('settingsBtn').addEventListener('click', () => {
  chrome.runtime.openOptionsPage();
});

document.getElementById('extractBtn').addEventListener('click', async () => {
  const query = document.getElementById('query').value.trim();
  const schemaStr = document.getElementById('schema').value.trim();
  const statusDiv = document.getElementById('status');
  const resultPre = document.getElementById('result');
  const extractBtn = document.getElementById('extractBtn');
  
  if (!query) {
    statusDiv.textContent = "Please enter an extraction query.";
    return;
  }
  
  let schema = null;
  if (schemaStr) {
    try {
      schema = JSON.parse(schemaStr);
    } catch (e) {
      statusDiv.textContent = "Invalid JSON schema format.";
      return;
    }
  }

  statusDiv.textContent = "Checking API Key...";
  resultPre.style.display = 'none';
  extractBtn.disabled = true;

  chrome.storage.sync.get(['apiKey'], async (result) => {
    const apiKey = result.apiKey;
    if (!apiKey) {
      statusDiv.textContent = "API Key missing. Click 'Open Settings' to configure.";
      extractBtn.disabled = false;
      return;
    }

    try {
      statusDiv.textContent = "Capturing active tab...";
      const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
      if (tabs.length === 0) {
        throw new Error("No active tab found");
      }

      const activeTab = tabs[0];
      const dataUrl = await chrome.tabs.captureVisibleTab(activeTab.windowId, { format: 'png' });
      
      statusDiv.textContent = "Extracting with Vision AI...";
      
      const payload = {
        image_base64: dataUrl,
        extraction_query: query,
        response_schema: schema
      };

      const response = await fetch('https://opticparse-python-sg.onrender.com/api/vision-scrape/direct', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-API-Key': apiKey
        },
        body: JSON.stringify(payload)
      });

      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`API Error ${response.status}: ${errorText}`);
      }

      const data = await response.json();
      
      statusDiv.textContent = "Extraction complete!";
      resultPre.textContent = JSON.stringify(data, null, 2);
      resultPre.style.display = 'block';

    } catch (err) {
      statusDiv.textContent = `Error: ${err.message}`;
    } finally {
      extractBtn.disabled = false;
    }
  });
});