sarangg commited on
Commit
a8b8a13
Β·
1 Parent(s): 65b9e81

Add Product Vision AI tab with Google Vision + CLIP fallback

Browse files
Files changed (3) hide show
  1. index.html +317 -233
  2. main.py +141 -74
  3. requirements.txt +4 -0
index.html CHANGED
@@ -4,7 +4,7 @@
4
  <head>
5
  <meta charset="UTF-8">
6
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
7
- <title>Image & PDF OCR AI</title>
8
  <style>
9
  :root {
10
  --primary: #8b5cf6;
@@ -29,7 +29,7 @@
29
  color: var(--text-color);
30
  display: flex;
31
  justify-content: center;
32
- align-items: center;
33
  min-height: 100vh;
34
  padding: 2rem;
35
  background-image: radial-gradient(circle at 15% 50%, rgba(139, 92, 246, 0.15), transparent 25%),
@@ -41,30 +41,66 @@
41
  border-radius: 1.5rem;
42
  padding: 2.5rem;
43
  width: 100%;
44
- max-width: 600px;
45
  box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);
46
  border: 1px solid rgba(255, 255, 255, 0.05);
47
- backdrop-filter: blur(10px);
48
  }
49
 
50
  h1 {
51
  text-align: center;
52
- font-size: 2rem;
53
- margin-bottom: 2rem;
54
  background: linear-gradient(to right, #a855f7, #3b82f6);
55
  -webkit-background-clip: text;
56
  background-clip: text;
57
  -webkit-text-fill-color: transparent;
58
  }
59
 
60
- .form-group {
 
 
 
61
  margin-bottom: 1.5rem;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  }
63
 
64
  label {
65
  display: block;
66
- margin-bottom: 0.5rem;
67
- font-size: 0.9rem;
68
  font-weight: 500;
69
  color: #cbd5e1;
70
  }
@@ -72,12 +108,12 @@
72
  input[type="text"],
73
  input[type="password"] {
74
  width: 100%;
75
- padding: 0.875rem 1rem;
76
  border-radius: 0.75rem;
77
  border: 1px solid var(--border-color);
78
  background-color: #0f172a;
79
  color: var(--text-color);
80
- font-size: 1rem;
81
  transition: border-color 0.2s, box-shadow 0.2s;
82
  }
83
 
@@ -88,6 +124,11 @@
88
  box-shadow: 0 0 0 3px rgba(139, 92, 246, 0.25);
89
  }
90
 
 
 
 
 
 
91
  .file-drop-area {
92
  position: relative;
93
  display: flex;
@@ -95,8 +136,7 @@
95
  justify-content: center;
96
  flex-direction: column;
97
  width: 100%;
98
- max-width: 100%;
99
- padding: 3rem 2rem;
100
  border: 2px dashed var(--border-color);
101
  border-radius: 1rem;
102
  transition: 0.2s;
@@ -112,7 +152,7 @@
112
  }
113
 
114
  .file-msg {
115
- font-size: 1rem;
116
  color: #94a3b8;
117
  pointer-events: none;
118
  }
@@ -129,7 +169,7 @@
129
 
130
  .preview-container {
131
  display: none;
132
- margin-top: 1.5rem;
133
  border-radius: 0.75rem;
134
  overflow: hidden;
135
  border: 1px solid var(--border-color);
@@ -139,35 +179,35 @@
139
 
140
  .preview-image {
141
  max-width: 100%;
142
- max-height: 250px;
143
  object-fit: contain;
144
  display: block;
145
  margin: 0 auto;
146
  }
147
 
148
- button {
149
  width: 100%;
150
- padding: 1rem;
151
  border: none;
152
  border-radius: 0.75rem;
153
  background: linear-gradient(135deg, var(--primary), #3b82f6);
154
  color: white;
155
- font-size: 1.1rem;
156
  font-weight: 600;
157
  cursor: pointer;
158
  transition: transform 0.1s, box-shadow 0.2s;
159
- margin-top: 1rem;
160
  }
161
 
162
- button:hover {
163
  box-shadow: 0 10px 15px -3px rgba(139, 92, 246, 0.4);
164
  }
165
 
166
- button:active {
167
  transform: scale(0.98);
168
  }
169
 
170
- button:disabled {
171
  opacity: 0.7;
172
  cursor: not-allowed;
173
  transform: none;
@@ -190,9 +230,24 @@
190
  }
191
  }
192
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
193
  .result-container {
194
  display: none;
195
- margin-top: 2rem;
196
  animation: fadeIn 0.5s;
197
  }
198
 
@@ -209,8 +264,8 @@
209
  }
210
 
211
  .result-title {
212
- font-size: 1.1rem;
213
- margin-bottom: 0.75rem;
214
  color: #94a3b8;
215
  display: flex;
216
  justify-content: space-between;
@@ -222,32 +277,17 @@
222
  border: 1px solid var(--border-color);
223
  border-radius: 0.75rem;
224
  padding: 1.25rem;
225
- min-height: 100px;
226
  white-space: pre-wrap;
227
  font-family: 'Courier New', Courier, monospace;
228
  color: #e2e8f0;
229
  line-height: 1.5;
230
- max-height: 300px;
231
  overflow-y: auto;
232
  }
233
 
234
- .status-msg {
235
- margin-top: 1rem;
236
- text-align: center;
237
- font-size: 0.9rem;
238
- display: none;
239
- }
240
-
241
- .status-error {
242
- color: var(--error-color);
243
- }
244
-
245
- .status-success {
246
- color: var(--success-color);
247
- }
248
-
249
  .copy-btn {
250
- background: transparent;
251
  border: 1px solid var(--border-color);
252
  padding: 0.25rem 0.75rem;
253
  font-size: 0.8rem;
@@ -256,36 +296,88 @@
256
  box-shadow: none;
257
  width: auto;
258
  margin: 0;
259
- background-color: var(--card-bg);
260
  }
261
 
262
  .copy-btn:hover {
263
  background-color: #334155;
264
- box-shadow: none;
265
  }
266
 
267
- .input-with-button {
 
 
 
 
 
 
268
  display: flex;
 
269
  gap: 0.5rem;
 
270
  }
271
 
272
- .inline-btn {
273
- margin-top: 0;
274
- padding: 0 1.5rem;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
275
  }
276
  </style>
277
  </head>
278
 
279
  <body>
280
-
281
  <div class="container">
282
- <h1>Image & PDF OCR AI</h1>
283
 
284
- <div class="form-group">
285
- <label for="apiUrl">API URL</label>
286
- <input type="text" id="apiUrl" placeholder="http://target-domain.com/ocr">
 
287
  </div>
288
 
 
 
 
 
 
289
  <div class="form-group">
290
  <label for="apiKey">API Key</label>
291
  <div class="input-with-button">
@@ -295,220 +387,212 @@
295
  </div>
296
  </div>
297
 
298
- <div class="form-group">
299
- <label>Upload Image</label>
300
- <div class="file-drop-area" id="dropArea">
301
- <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none"
302
- stroke="#94a3b8" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
303
- style="margin-bottom: 1rem;">
304
- <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
305
- <polyline points="17 8 12 3 7 8"></polyline>
306
- <line x1="12" y1="3" x2="12" y2="15"></line>
307
- </svg>
308
- <span class="file-msg">Drag & drop or click to choose an image or PDF</span>
309
- <input class="file-input" type="file" id="fileInput" accept="image/*,.pdf">
 
 
 
 
310
  </div>
311
-
312
- <div class="preview-container" id="previewContainer">
313
- <img class="preview-image" id="previewImage" src="" alt="Image Preview">
 
 
 
 
 
 
 
 
314
  </div>
315
  </div>
316
 
317
- <button id="submitBtn">
318
- <span id="btnText">Extract Text</span>
319
- <div class="spinner" id="spinner"></div>
320
- </button>
321
-
322
- <div id="statusMsg" class="status-msg"></div>
323
-
324
- <div class="result-container" id="resultContainer">
325
- <div class="result-title">
326
- <span>Extracted Text</span>
327
- <button class="copy-btn" id="copyBtn">Copy</button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
328
  </div>
329
- <div class="result-box" id="resultBox"></div>
330
  </div>
331
  </div>
332
 
333
  <script>
334
- const fileInput = document.getElementById('fileInput');
335
- const dropArea = document.getElementById('dropArea');
336
- const previewContainer = document.getElementById('previewContainer');
337
- const previewImage = document.getElementById('previewImage');
338
- const submitBtn = document.getElementById('submitBtn');
339
- const btnText = document.getElementById('btnText');
340
- const spinner = document.getElementById('spinner');
341
- const resultContainer = document.getElementById('resultContainer');
342
- const resultBox = document.getElementById('resultBox');
343
- const statusMsg = document.getElementById('statusMsg');
344
- const copyBtn = document.getElementById('copyBtn');
345
- const copyApiKeyBtn = document.getElementById('copyApiKeyBtn');
346
-
347
- // Auto-detect the correct API URL based on where this page is being served from
348
- const apiUrlInput = document.getElementById('apiUrl');
349
- const host = window.location.hostname;
350
- let baseUrl;
351
- if (host === 'localhost' || host === '127.0.0.1') {
352
- baseUrl = 'http://localhost:4002';
353
- } else {
354
- // On HuggingFace Spaces or any other public host, use same origin
355
- baseUrl = window.location.protocol + '//' + window.location.host;
356
- }
357
- apiUrlInput.value = baseUrl + '/ocr';
358
-
359
- let selectedFile = null;
360
-
361
- // Handle drag and drop events
362
- ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
363
- dropArea.addEventListener(eventName, preventDefaults, false);
364
- });
365
-
366
- function preventDefaults(e) {
367
- e.preventDefault();
368
- e.stopPropagation();
369
- }
370
-
371
- ['dragenter', 'dragover'].forEach(eventName => {
372
- dropArea.addEventListener(eventName, () => dropArea.classList.add('dragover'), false);
373
- });
374
-
375
- ['dragleave', 'drop'].forEach(eventName => {
376
- dropArea.addEventListener(eventName, () => dropArea.classList.remove('dragover'), false);
377
- });
378
-
379
- dropArea.addEventListener('drop', handleDrop, false);
380
-
381
- function handleDrop(e) {
382
- const dt = e.dataTransfer;
383
- const files = dt.files;
384
- handleFiles(files);
385
  }
386
 
387
- fileInput.addEventListener('change', function () {
388
- handleFiles(this.files);
 
 
 
 
 
 
 
 
 
 
 
 
389
  });
390
 
391
- function handleFiles(files) {
392
- if (files.length > 0) {
 
 
 
 
 
 
 
 
 
 
 
 
 
393
  selectedFile = files[0];
394
  const isPdf = selectedFile.type === 'application/pdf' || selectedFile.name.endsWith('.pdf');
395
- const isImage = selectedFile.type.startsWith('image/');
396
-
397
- if (!isPdf && !isImage) {
398
- showStatus('Please select an image or PDF file.', false);
399
- selectedFile = null;
400
- return;
401
  }
402
-
403
  if (isPdf) {
404
- // Show PDF file name instead of image preview
405
- previewContainer.innerHTML = `<div style="padding:1.5rem;text-align:center;font-size:1rem;color:#94a3b8;">πŸ“„ <strong style="color:#e2e8f0">${selectedFile.name}</strong><br><small>${(selectedFile.size / 1024).toFixed(1)} KB</small></div>`;
406
- previewContainer.style.display = 'block';
407
- dropArea.style.display = 'none';
408
  } else {
409
- // Show image preview
410
- const reader = new FileReader();
411
- reader.readAsDataURL(selectedFile);
412
- reader.onloadend = function () {
413
- previewContainer.innerHTML = `<img class="preview-image" src="${reader.result}" alt="Image Preview">`;
414
- previewContainer.style.display = 'block';
415
- dropArea.style.display = 'none';
416
- }
417
  }
418
-
419
- statusMsg.style.display = 'none';
420
- resultContainer.style.display = 'none';
421
  }
 
 
 
422
  }
423
 
424
- // Double click on preview to re-upload
425
- previewContainer.addEventListener('dblclick', () => {
426
- fileInput.click();
427
- });
 
 
 
 
428
 
429
- // Suggest double click to change image
430
- previewContainer.title = "Double click to change image";
 
 
 
 
431
 
432
- submitBtn.addEventListener('click', async () => {
 
 
 
433
  const apiUrl = document.getElementById('apiUrl').value.trim();
434
  const apiKey = document.getElementById('apiKey').value.trim();
435
-
436
- if (!selectedFile) {
437
- showStatus('Please select an image first.', false);
438
- return;
439
- }
440
-
441
- if (!apiUrl) {
442
- showStatus('Please provide the API URL.', false);
443
- return;
444
- }
445
-
446
- // Set Loading State
447
- submitBtn.disabled = true;
448
- btnText.style.display = 'none';
449
- spinner.style.display = 'block';
450
- statusMsg.style.display = 'none';
451
- resultContainer.style.display = 'none';
452
-
453
- const formData = new FormData();
454
- formData.append('file', selectedFile);
455
-
456
  try {
457
- const response = await fetch(apiUrl, {
458
- method: 'POST',
459
- headers: {
460
- 'x-api-key': apiKey
461
- },
462
- body: formData
463
- });
464
-
465
- const data = await response.json();
466
-
467
- if (response.ok) {
468
- showStatus('Text extracted successfully!', true);
469
- if (data.extracted_text) {
470
- resultBox.textContent = data.extracted_text;
471
- } else {
472
- resultBox.innerHTML = '<i>No text was found in the image.</i>';
473
- }
474
- resultContainer.style.display = 'block';
475
  } else {
476
- showStatus(`Error: ${data.detail || 'Failed to process image.'}`, false);
477
  }
478
- } catch (error) {
479
- showStatus(`Network Error: ${error.message}. Ensure the API URL is correct and the server is running.`, false);
480
- } finally {
481
- // Reset Loading State
482
- submitBtn.disabled = false;
483
- btnText.style.display = 'block';
484
- spinner.style.display = 'none';
485
- }
486
  });
487
 
488
- function showStatus(msg, isSuccess) {
489
- statusMsg.textContent = msg;
490
- statusMsg.style.display = 'block';
491
- statusMsg.className = 'status-msg ' + (isSuccess ? 'status-success' : 'status-error');
492
- }
493
-
494
- copyBtn.addEventListener('click', () => {
495
- navigator.clipboard.writeText(resultBox.textContent).then(() => {
496
- const originalText = copyBtn.textContent;
497
- copyBtn.textContent = "Copied!";
498
- setTimeout(() => { copyBtn.textContent = originalText; }, 2000);
499
  });
500
  });
501
 
502
- copyApiKeyBtn.addEventListener('click', () => {
503
- const apiKeyInput = document.getElementById('apiKey');
504
- navigator.clipboard.writeText(apiKeyInput.value).then(() => {
505
- const originalText = copyApiKeyBtn.textContent;
506
- copyApiKeyBtn.textContent = "Copied!";
507
- setTimeout(() => { copyApiKeyBtn.textContent = originalText; }, 2000);
508
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
509
  });
510
  </script>
511
-
512
  </body>
513
 
514
  </html>
 
4
  <head>
5
  <meta charset="UTF-8">
6
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
7
+ <title>Image & PDF OCR + Vision AI</title>
8
  <style>
9
  :root {
10
  --primary: #8b5cf6;
 
29
  color: var(--text-color);
30
  display: flex;
31
  justify-content: center;
32
+ align-items: flex-start;
33
  min-height: 100vh;
34
  padding: 2rem;
35
  background-image: radial-gradient(circle at 15% 50%, rgba(139, 92, 246, 0.15), transparent 25%),
 
41
  border-radius: 1.5rem;
42
  padding: 2.5rem;
43
  width: 100%;
44
+ max-width: 620px;
45
  box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);
46
  border: 1px solid rgba(255, 255, 255, 0.05);
 
47
  }
48
 
49
  h1 {
50
  text-align: center;
51
+ font-size: 1.8rem;
52
+ margin-bottom: 1.5rem;
53
  background: linear-gradient(to right, #a855f7, #3b82f6);
54
  -webkit-background-clip: text;
55
  background-clip: text;
56
  -webkit-text-fill-color: transparent;
57
  }
58
 
59
+ /* Tabs */
60
+ .tabs {
61
+ display: flex;
62
+ gap: 0.5rem;
63
  margin-bottom: 1.5rem;
64
+ background: #0f172a;
65
+ border-radius: 0.75rem;
66
+ padding: 0.25rem;
67
+ }
68
+
69
+ .tab-btn {
70
+ flex: 1;
71
+ padding: 0.6rem;
72
+ border: none;
73
+ border-radius: 0.5rem;
74
+ background: transparent;
75
+ color: #94a3b8;
76
+ font-size: 0.9rem;
77
+ font-weight: 600;
78
+ cursor: pointer;
79
+ transition: all 0.2s;
80
+ }
81
+
82
+ .tab-btn.active {
83
+ background: linear-gradient(135deg, var(--primary), #3b82f6);
84
+ color: white;
85
+ }
86
+
87
+ .tab-panel {
88
+ display: none;
89
+ }
90
+
91
+ .tab-panel.active {
92
+ display: block;
93
+ }
94
+
95
+ /* Shared fields */
96
+ .form-group {
97
+ margin-bottom: 1.25rem;
98
  }
99
 
100
  label {
101
  display: block;
102
+ margin-bottom: 0.4rem;
103
+ font-size: 0.85rem;
104
  font-weight: 500;
105
  color: #cbd5e1;
106
  }
 
108
  input[type="text"],
109
  input[type="password"] {
110
  width: 100%;
111
+ padding: 0.75rem 1rem;
112
  border-radius: 0.75rem;
113
  border: 1px solid var(--border-color);
114
  background-color: #0f172a;
115
  color: var(--text-color);
116
+ font-size: 0.95rem;
117
  transition: border-color 0.2s, box-shadow 0.2s;
118
  }
119
 
 
124
  box-shadow: 0 0 0 3px rgba(139, 92, 246, 0.25);
125
  }
126
 
127
+ .input-with-button {
128
+ display: flex;
129
+ gap: 0.5rem;
130
+ }
131
+
132
  .file-drop-area {
133
  position: relative;
134
  display: flex;
 
136
  justify-content: center;
137
  flex-direction: column;
138
  width: 100%;
139
+ padding: 2.5rem 2rem;
 
140
  border: 2px dashed var(--border-color);
141
  border-radius: 1rem;
142
  transition: 0.2s;
 
152
  }
153
 
154
  .file-msg {
155
+ font-size: 0.95rem;
156
  color: #94a3b8;
157
  pointer-events: none;
158
  }
 
169
 
170
  .preview-container {
171
  display: none;
172
+ margin-top: 1rem;
173
  border-radius: 0.75rem;
174
  overflow: hidden;
175
  border: 1px solid var(--border-color);
 
179
 
180
  .preview-image {
181
  max-width: 100%;
182
+ max-height: 200px;
183
  object-fit: contain;
184
  display: block;
185
  margin: 0 auto;
186
  }
187
 
188
+ button.primary-btn {
189
  width: 100%;
190
+ padding: 0.9rem;
191
  border: none;
192
  border-radius: 0.75rem;
193
  background: linear-gradient(135deg, var(--primary), #3b82f6);
194
  color: white;
195
+ font-size: 1rem;
196
  font-weight: 600;
197
  cursor: pointer;
198
  transition: transform 0.1s, box-shadow 0.2s;
199
+ margin-top: 0.75rem;
200
  }
201
 
202
+ button.primary-btn:hover {
203
  box-shadow: 0 10px 15px -3px rgba(139, 92, 246, 0.4);
204
  }
205
 
206
+ button.primary-btn:active {
207
  transform: scale(0.98);
208
  }
209
 
210
+ button.primary-btn:disabled {
211
  opacity: 0.7;
212
  cursor: not-allowed;
213
  transform: none;
 
230
  }
231
  }
232
 
233
+ .status-msg {
234
+ margin-top: 0.75rem;
235
+ text-align: center;
236
+ font-size: 0.85rem;
237
+ display: none;
238
+ }
239
+
240
+ .status-error {
241
+ color: var(--error-color);
242
+ }
243
+
244
+ .status-success {
245
+ color: var(--success-color);
246
+ }
247
+
248
  .result-container {
249
  display: none;
250
+ margin-top: 1.5rem;
251
  animation: fadeIn 0.5s;
252
  }
253
 
 
264
  }
265
 
266
  .result-title {
267
+ font-size: 1rem;
268
+ margin-bottom: 0.6rem;
269
  color: #94a3b8;
270
  display: flex;
271
  justify-content: space-between;
 
277
  border: 1px solid var(--border-color);
278
  border-radius: 0.75rem;
279
  padding: 1.25rem;
280
+ min-height: 80px;
281
  white-space: pre-wrap;
282
  font-family: 'Courier New', Courier, monospace;
283
  color: #e2e8f0;
284
  line-height: 1.5;
285
+ max-height: 280px;
286
  overflow-y: auto;
287
  }
288
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
289
  .copy-btn {
290
+ background: var(--card-bg);
291
  border: 1px solid var(--border-color);
292
  padding: 0.25rem 0.75rem;
293
  font-size: 0.8rem;
 
296
  box-shadow: none;
297
  width: auto;
298
  margin: 0;
299
+ cursor: pointer;
300
  }
301
 
302
  .copy-btn:hover {
303
  background-color: #334155;
 
304
  }
305
 
306
+ .inline-btn {
307
+ margin-top: 0;
308
+ padding: 0 1.25rem;
309
+ }
310
+
311
+ /* Classification result tags */
312
+ .label-tags {
313
  display: flex;
314
+ flex-wrap: wrap;
315
  gap: 0.5rem;
316
+ margin-top: 0.75rem;
317
  }
318
 
319
+ .label-tag {
320
+ padding: 0.3rem 0.75rem;
321
+ border-radius: 9999px;
322
+ font-size: 0.8rem;
323
+ font-weight: 600;
324
+ }
325
+
326
+ .label-tag:nth-child(1) {
327
+ background: rgba(139, 92, 246, 0.25);
328
+ color: #c4b5fd;
329
+ border: 1px solid rgba(139, 92, 246, 0.4);
330
+ }
331
+
332
+ .label-tag:nth-child(n+2) {
333
+ background: rgba(51, 65, 85, 0.5);
334
+ color: #94a3b8;
335
+ border: 1px solid var(--border-color);
336
+ }
337
+
338
+ .source-badge {
339
+ font-size: 0.75rem;
340
+ padding: 0.2rem 0.6rem;
341
+ border-radius: 9999px;
342
+ font-weight: 600;
343
+ }
344
+
345
+ .badge-google {
346
+ background: rgba(16, 185, 129, 0.15);
347
+ color: #34d399;
348
+ border: 1px solid rgba(16, 185, 129, 0.3);
349
+ }
350
+
351
+ .badge-clip {
352
+ background: rgba(59, 130, 246, 0.15);
353
+ color: #60a5fa;
354
+ border: 1px solid rgba(59, 130, 246, 0.3);
355
+ }
356
+
357
+ .category-display {
358
+ font-size: 1.4rem;
359
+ font-weight: 700;
360
+ color: #fff;
361
+ margin-bottom: 0.5rem;
362
  }
363
  </style>
364
  </head>
365
 
366
  <body>
 
367
  <div class="container">
368
+ <h1>πŸ” OCR & Vision AI</h1>
369
 
370
+ <!-- Tabs -->
371
+ <div class="tabs">
372
+ <button class="tab-btn active" id="tabOcr" onclick="switchTab('ocr')">πŸ“„ Extract Text (OCR)</button>
373
+ <button class="tab-btn" id="tabVision" onclick="switchTab('vision')">πŸ›οΈ Identify Product</button>
374
  </div>
375
 
376
+ <!-- Shared: API URL + Key -->
377
+ <div class="form-group">
378
+ <label for="apiUrl">API URL Base</label>
379
+ <input type="text" id="apiUrl" placeholder="https://yourapp.hf.space">
380
+ </div>
381
  <div class="form-group">
382
  <label for="apiKey">API Key</label>
383
  <div class="input-with-button">
 
387
  </div>
388
  </div>
389
 
390
+ <!-- ───── OCR TAB ───── -->
391
+ <div class="tab-panel active" id="panelOcr">
392
+ <div class="form-group">
393
+ <label>Upload Image or PDF</label>
394
+ <div class="file-drop-area" id="dropAreaOcr">
395
+ <svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 24 24" fill="none"
396
+ stroke="#94a3b8" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
397
+ style="margin-bottom:0.75rem">
398
+ <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
399
+ <polyline points="17 8 12 3 7 8" />
400
+ <line x1="12" y1="3" x2="12" y2="15" />
401
+ </svg>
402
+ <span class="file-msg">Drag & drop or click β€” Image or PDF</span>
403
+ <input class="file-input" type="file" id="fileInputOcr" accept="image/*,.pdf">
404
+ </div>
405
+ <div class="preview-container" id="previewOcr"></div>
406
  </div>
407
+ <button class="primary-btn" id="submitOcr">
408
+ <span id="btnTextOcr">Extract Text</span>
409
+ <div class="spinner" id="spinnerOcr"></div>
410
+ </button>
411
+ <div id="statusOcr" class="status-msg"></div>
412
+ <div class="result-container" id="resultOcr">
413
+ <div class="result-title">
414
+ <span>Extracted Text</span>
415
+ <button class="copy-btn" id="copyOcrBtn">Copy</button>
416
+ </div>
417
+ <div class="result-box" id="resultBoxOcr"></div>
418
  </div>
419
  </div>
420
 
421
+ <!-- ───── VISION TAB ───── -->
422
+ <div class="tab-panel" id="panelVision">
423
+ <div class="form-group">
424
+ <label>Upload Product Image</label>
425
+ <div class="file-drop-area" id="dropAreaVision">
426
+ <svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 24 24" fill="none"
427
+ stroke="#94a3b8" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
428
+ style="margin-bottom:0.75rem">
429
+ <rect x="3" y="3" width="18" height="18" rx="2" />
430
+ <circle cx="8.5" cy="8.5" r="1.5" />
431
+ <polyline points="21 15 16 10 5 21" />
432
+ </svg>
433
+ <span class="file-msg">Drag & drop or click β€” Image only</span>
434
+ <input class="file-input" type="file" id="fileInputVision" accept="image/*">
435
+ </div>
436
+ <div class="preview-container" id="previewVision"></div>
437
+ </div>
438
+ <button class="primary-btn" id="submitVision">
439
+ <span id="btnTextVision">Identify Product</span>
440
+ <div class="spinner" id="spinnerVision"></div>
441
+ </button>
442
+ <div id="statusVision" class="status-msg"></div>
443
+ <div class="result-container" id="resultVision">
444
+ <div class="result-title">
445
+ <span>Result</span>
446
+ <span id="sourceBadge" class="source-badge"></span>
447
+ </div>
448
+ <div class="category-display" id="categoryDisplay"></div>
449
+ <div class="label-tags" id="labelTags"></div>
450
  </div>
 
451
  </div>
452
  </div>
453
 
454
  <script>
455
+ // ── Tab switching ─────────────────────────────────────────────────────────
456
+ function switchTab(tab) {
457
+ document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
458
+ document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
459
+ document.getElementById('tab' + (tab === 'ocr' ? 'Ocr' : 'Vision')).classList.add('active');
460
+ document.getElementById('panel' + (tab === 'ocr' ? 'Ocr' : 'Vision')).classList.add('active');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
461
  }
462
 
463
+ // ── Auto-detect API base URL ──────────────────────────────────────────────
464
+ const apiUrlInput = document.getElementById('apiUrl');
465
+ const host = window.location.hostname;
466
+ apiUrlInput.value = (host === 'localhost' || host === '127.0.0.1')
467
+ ? 'http://localhost:4002'
468
+ : window.location.protocol + '//' + window.location.host;
469
+
470
+ // ── Copy API Key ──────────────────────────────────────────────────────────
471
+ document.getElementById('copyApiKeyBtn').addEventListener('click', () => {
472
+ navigator.clipboard.writeText(document.getElementById('apiKey').value).then(() => {
473
+ const btn = document.getElementById('copyApiKeyBtn');
474
+ btn.textContent = 'Copied!';
475
+ setTimeout(() => btn.textContent = 'Copy', 2000);
476
+ });
477
  });
478
 
479
+ // ── Generic file drop setup ───────────────────────────────────────────────
480
+ function setupDrop(dropAreaId, fileInputId, previewId, acceptPdf = false) {
481
+ const dropArea = document.getElementById(dropAreaId);
482
+ const fileInput = document.getElementById(fileInputId);
483
+ const preview = document.getElementById(previewId);
484
+ let selectedFile = null;
485
+
486
+ ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(ev => dropArea.addEventListener(ev, e => { e.preventDefault(); e.stopPropagation(); }));
487
+ ['dragenter', 'dragover'].forEach(ev => dropArea.addEventListener(ev, () => dropArea.classList.add('dragover')));
488
+ ['dragleave', 'drop'].forEach(ev => dropArea.addEventListener(ev, () => dropArea.classList.remove('dragover')));
489
+ dropArea.addEventListener('drop', e => handleFiles(e.dataTransfer.files));
490
+ fileInput.addEventListener('change', function () { handleFiles(this.files); });
491
+
492
+ function handleFiles(files) {
493
+ if (!files.length) return;
494
  selectedFile = files[0];
495
  const isPdf = selectedFile.type === 'application/pdf' || selectedFile.name.endsWith('.pdf');
496
+ const isImg = selectedFile.type.startsWith('image/');
497
+ if (!isImg && !(acceptPdf && isPdf)) {
498
+ alert('Please select a valid file.');
499
+ selectedFile = null; return;
 
 
500
  }
 
501
  if (isPdf) {
502
+ 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>`;
 
 
 
503
  } else {
504
+ const fr = new FileReader();
505
+ fr.onloadend = () => { preview.innerHTML = `<img class="preview-image" src="${fr.result}" alt="preview">`; };
506
+ fr.readAsDataURL(selectedFile);
 
 
 
 
 
507
  }
508
+ preview.style.display = 'block';
509
+ dropArea.style.display = 'none';
 
510
  }
511
+
512
+ preview.addEventListener('dblclick', () => { fileInput.click(); dropArea.style.display = ''; preview.style.display = 'none'; });
513
+ return { getFile: () => selectedFile };
514
  }
515
 
516
+ const ocrDrop = setupDrop('dropAreaOcr', 'fileInputOcr', 'previewOcr', true);
517
+ const visionDrop = setupDrop('dropAreaVision', 'fileInputVision', 'previewVision', false);
518
+
519
+ function setLoading(btnTextId, spinnerId, btnId, loading) {
520
+ document.getElementById(btnTextId).style.display = loading ? 'none' : 'block';
521
+ document.getElementById(spinnerId).style.display = loading ? 'block' : 'none';
522
+ document.getElementById(btnId).disabled = loading;
523
+ }
524
 
525
+ function showStatus(id, msg, ok) {
526
+ const el = document.getElementById(id);
527
+ el.textContent = msg;
528
+ el.className = 'status-msg ' + (ok ? 'status-success' : 'status-error');
529
+ el.style.display = 'block';
530
+ }
531
 
532
+ // ── OCR submit ────────────────────────────────────────────────────────────
533
+ document.getElementById('submitOcr').addEventListener('click', async () => {
534
+ const file = ocrDrop.getFile();
535
+ if (!file) return showStatus('statusOcr', 'Please select a file.', false);
536
  const apiUrl = document.getElementById('apiUrl').value.trim();
537
  const apiKey = document.getElementById('apiKey').value.trim();
538
+ setLoading('btnTextOcr', 'spinnerOcr', 'submitOcr', true);
539
+ document.getElementById('statusOcr').style.display = 'none';
540
+ document.getElementById('resultOcr').style.display = 'none';
541
+ const fd = new FormData(); fd.append('file', file);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
542
  try {
543
+ const res = await fetch(apiUrl + '/ocr', { method: 'POST', headers: { 'x-api-key': apiKey }, body: fd });
544
+ const data = await res.json();
545
+ if (res.ok) {
546
+ showStatus('statusOcr', 'Text extracted successfully!', true);
547
+ document.getElementById('resultBoxOcr').textContent = data.extracted_text || '(No text found)';
548
+ document.getElementById('resultOcr').style.display = 'block';
 
 
 
 
 
 
 
 
 
 
 
 
549
  } else {
550
+ showStatus('statusOcr', 'Error: ' + (data.detail || 'Unknown error'), false);
551
  }
552
+ } catch (e) { showStatus('statusOcr', 'Network Error: ' + e.message, false); }
553
+ finally { setLoading('btnTextOcr', 'spinnerOcr', 'submitOcr', false); }
 
 
 
 
 
 
554
  });
555
 
556
+ document.getElementById('copyOcrBtn').addEventListener('click', () => {
557
+ navigator.clipboard.writeText(document.getElementById('resultBoxOcr').textContent).then(() => {
558
+ const btn = document.getElementById('copyOcrBtn');
559
+ btn.textContent = 'Copied!';
560
+ setTimeout(() => btn.textContent = 'Copy', 2000);
 
 
 
 
 
 
561
  });
562
  });
563
 
564
+ // ── Vision submit ─────────────────────────────────────────────────────────
565
+ document.getElementById('submitVision').addEventListener('click', async () => {
566
+ const file = visionDrop.getFile();
567
+ if (!file) return showStatus('statusVision', 'Please select an image.', false);
568
+ const apiUrl = document.getElementById('apiUrl').value.trim();
569
+ const apiKey = document.getElementById('apiKey').value.trim();
570
+ setLoading('btnTextVision', 'spinnerVision', 'submitVision', true);
571
+ document.getElementById('statusVision').style.display = 'none';
572
+ document.getElementById('resultVision').style.display = 'none';
573
+ const fd = new FormData(); fd.append('file', file);
574
+ try {
575
+ const res = await fetch(apiUrl + '/classify', { method: 'POST', headers: { 'x-api-key': apiKey }, body: fd });
576
+ const data = await res.json();
577
+ if (res.ok) {
578
+ showStatus('statusVision', 'Product identified!', true);
579
+ // Category
580
+ document.getElementById('categoryDisplay').textContent = '🏷️ ' + data.category;
581
+ // Source badge
582
+ const badge = document.getElementById('sourceBadge');
583
+ if (data.source === 'google_vision') { badge.textContent = '⚑ Google Vision'; badge.className = 'source-badge badge-google'; }
584
+ else { badge.textContent = 'πŸ€– CLIP AI'; badge.className = 'source-badge badge-clip'; }
585
+ // Label tags
586
+ const tagsEl = document.getElementById('labelTags');
587
+ tagsEl.innerHTML = data.labels.map(l => `<span class="label-tag">${l}</span>`).join('');
588
+ document.getElementById('resultVision').style.display = 'block';
589
+ } else {
590
+ showStatus('statusVision', 'Error: ' + (data.detail || 'Unknown error'), false);
591
+ }
592
+ } catch (e) { showStatus('statusVision', 'Network Error: ' + e.message, false); }
593
+ finally { setLoading('btnTextVision', 'spinnerVision', 'submitVision', false); }
594
  });
595
  </script>
 
596
  </body>
597
 
598
  </html>
main.py CHANGED
@@ -4,10 +4,10 @@ from fastapi.responses import FileResponse
4
  from fastapi.security import APIKeyHeader
5
  import io
6
  import os
 
7
 
8
- app = FastAPI(title="Image OCR API")
9
 
10
- # Add CORS middleware to allow other websites to connect
11
  app.add_middleware(
12
  CORSMiddleware,
13
  allow_origins=["*"],
@@ -16,108 +16,175 @@ app.add_middleware(
16
  allow_headers=["*"],
17
  )
18
 
19
- # Lazy-load the OCR reader β€” only initializes on first use, not at startup
20
- _reader = None
 
 
21
 
22
- def get_reader():
23
- global _reader
24
- if _reader is None:
25
  import easyocr
26
- print("Loading OCR Model for the first time... Please wait!")
27
- _reader = easyocr.Reader(['en'])
28
- print("OCR Model loaded successfully!")
29
- return _reader
30
-
31
- # Define the API Key (strong 0-9, a-z, A-Z pattern)
32
- API_KEY = os.environ.get("API_KEY", "xkLm9Qz4BvWtUa2Nf8PjX1")
 
 
 
 
 
 
 
 
 
33
  API_KEY_NAME = "x-api-key"
34
  api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False)
35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  def get_api_key(api_key: str = Depends(api_key_header)):
37
  if api_key == API_KEY:
38
  return api_key
39
- raise HTTPException(
40
- status_code=status.HTTP_401_UNAUTHORIZED,
41
- detail="Invalid or missing API Key"
42
- )
43
 
 
44
  def extract_text_from_image_bytes(image_bytes: bytes) -> str:
45
- """Run EasyOCR on raw image bytes and return extracted text."""
46
- reader = get_reader()
47
  result = reader.readtext(image_bytes, detail=0)
48
  return "\n".join(result)
49
 
50
  def process_pdf(pdf_bytes: bytes) -> str:
51
- """Convert each PDF page to an image and run OCR on it."""
52
- import fitz # PyMuPDF
53
- from PIL import Image
54
- import io as _io
55
-
56
  doc = fitz.open(stream=pdf_bytes, filetype="pdf")
57
- all_pages_text = []
58
-
59
- for page_num in range(len(doc)):
60
- page = doc.load_page(page_num)
61
- # Render page at 2x scale for better OCR accuracy
62
- mat = fitz.Matrix(2, 2)
63
- pix = page.get_pixmap(matrix=mat)
64
- img_bytes = pix.tobytes("png")
65
-
66
- page_text = extract_text_from_image_bytes(img_bytes)
67
- if page_text.strip():
68
- all_pages_text.append(f"--- Page {page_num + 1} ---\n{page_text}")
69
-
70
  doc.close()
71
- return "\n\n".join(all_pages_text)
72
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  @app.get("/", tags=["UI"])
74
  async def serve_ui():
75
- """Serves the main frontend Web UI."""
76
- try:
77
- return FileResponse("index.html")
78
- except Exception:
79
- raise HTTPException(status_code=404, detail="index.html not found.")
80
 
81
  @app.post("/ocr", tags=["OCR"])
82
  async def perform_ocr(
83
  api_key: str = Depends(get_api_key),
84
  file: UploadFile = File(...)
85
  ):
86
- """
87
- Endpoint to receive an image OR a PDF and extract all text from it.
88
- Ensure you include the 'x-api-key' header with your request.
89
- - Supports image formats: PNG, JPG, JPEG, BMP, WEBP, TIFF
90
- - Supports PDF files (multi-page supported)
91
- """
92
- contents = await file.read()
93
- filename = file.filename or ""
94
  content_type = file.content_type or ""
95
-
96
- is_pdf = content_type == "application/pdf" or filename.lower().endswith(".pdf")
97
  is_image = content_type.startswith("image/")
98
-
99
  if not is_pdf and not is_image:
100
- raise HTTPException(
101
- status_code=400,
102
- detail="Invalid file type. Please upload an image (PNG, JPG…) or a PDF."
103
- )
 
 
 
104
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
  try:
106
- if is_pdf:
107
- extracted_text = process_pdf(contents)
108
- file_type = "pdf"
109
- else:
110
- extracted_text = extract_text_from_image_bytes(contents)
111
- file_type = "image"
112
-
113
- return {
114
- "success": True,
115
- "filename": filename,
116
- "file_type": file_type,
117
- "extracted_text": extracted_text.strip()
118
- }
119
  except Exception as e:
120
- raise HTTPException(status_code=500, detail=f"OCR Processing failed: {str(e)}")
121
 
122
  if __name__ == "__main__":
123
  import uvicorn
 
4
  from fastapi.security import APIKeyHeader
5
  import io
6
  import os
7
+ import requests
8
 
9
+ app = FastAPI(title="Image OCR & Vision API")
10
 
 
11
  app.add_middleware(
12
  CORSMiddleware,
13
  allow_origins=["*"],
 
16
  allow_headers=["*"],
17
  )
18
 
19
+ # ── Lazy model holders ────────────────────────────────────────────────────────
20
+ _ocr_reader = None
21
+ _clip_model = None
22
+ _clip_processor = None
23
 
24
+ def get_ocr_reader():
25
+ global _ocr_reader
26
+ if _ocr_reader is None:
27
  import easyocr
28
+ print("Loading EasyOCR model...")
29
+ _ocr_reader = easyocr.Reader(['en'])
30
+ return _ocr_reader
31
+
32
+ def get_clip():
33
+ global _clip_model, _clip_processor
34
+ if _clip_model is None:
35
+ from transformers import CLIPProcessor, CLIPModel
36
+ print("Loading CLIP model...")
37
+ _clip_model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
38
+ _clip_processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
39
+ print("CLIP model loaded!")
40
+ return _clip_model, _clip_processor
41
+
42
+ # ── API Key ───────────────────────────────────────────────────────────────────
43
+ API_KEY = os.environ.get("API_KEY", "xkLm9Qz4BvWtUa2Nf8PjX1")
44
  API_KEY_NAME = "x-api-key"
45
  api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False)
46
 
47
+ GOOGLE_VISION_API_KEY = os.environ.get("GOOGLE_VISION_API_KEY", "")
48
+
49
+ # Common product categories used by CLIP fallback
50
+ CLIP_CATEGORIES = [
51
+ "shoes", "sneakers", "boots", "sandals",
52
+ "shirt", "t-shirt", "dress", "jacket", "coat", "hoodie", "jeans", "pants", "skirt",
53
+ "laptop", "smartphone", "tablet", "headphones", "camera", "smartwatch", "keyboard", "mouse",
54
+ "handbag", "backpack", "wallet", "sunglasses", "watch", "jewelry", "necklace",
55
+ "sofa", "chair", "table", "lamp", "bed", "shelf",
56
+ "book", "toy", "game controller", "bicycle", "car accessory",
57
+ "food", "drink", "bottle", "cup", "plate",
58
+ "cosmetics", "perfume", "skincare product", "medicine"
59
+ ]
60
+
61
  def get_api_key(api_key: str = Depends(api_key_header)):
62
  if api_key == API_KEY:
63
  return api_key
64
+ raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid or missing API Key")
 
 
 
65
 
66
+ # ── OCR helpers ───────────────────────────────────────────────────────────────
67
  def extract_text_from_image_bytes(image_bytes: bytes) -> str:
68
+ reader = get_ocr_reader()
 
69
  result = reader.readtext(image_bytes, detail=0)
70
  return "\n".join(result)
71
 
72
  def process_pdf(pdf_bytes: bytes) -> str:
73
+ import fitz
 
 
 
 
74
  doc = fitz.open(stream=pdf_bytes, filetype="pdf")
75
+ pages = []
76
+ for i in range(len(doc)):
77
+ page = doc.load_page(i)
78
+ pix = page.get_pixmap(matrix=fitz.Matrix(2, 2))
79
+ text = extract_text_from_image_bytes(pix.tobytes("png"))
80
+ if text.strip():
81
+ pages.append(f"--- Page {i+1} ---\n{text}")
 
 
 
 
 
 
82
  doc.close()
83
+ return "\n\n".join(pages)
84
+
85
+ # ── Vision / Classification helpers ──────────────────────────────────────────
86
+ def classify_with_google(image_bytes: bytes) -> dict | None:
87
+ """Try Google Vision API. Returns None if key missing or quota exceeded."""
88
+ if not GOOGLE_VISION_API_KEY:
89
+ return None
90
+ import base64
91
+ encoded = base64.b64encode(image_bytes).decode("utf-8")
92
+ payload = {
93
+ "requests": [{
94
+ "image": {"content": encoded},
95
+ "features": [
96
+ {"type": "LABEL_DETECTION", "maxResults": 10},
97
+ {"type": "OBJECT_LOCALIZATION","maxResults": 5},
98
+ ]
99
+ }]
100
+ }
101
+ url = f"https://vision.googleapis.com/v1/images:annotate?key={GOOGLE_VISION_API_KEY}"
102
+ resp = requests.post(url, json=payload, timeout=15)
103
+ if resp.status_code == 429 or resp.status_code == 403:
104
+ # Quota exhausted or billing issue β€” trigger fallback
105
+ return None
106
+ resp.raise_for_status()
107
+ data = resp.json()["responses"][0]
108
+ labels = [l["description"] for l in data.get("labelAnnotations", [])]
109
+ objects = [o["name"] for o in data.get("localizedObjectAnnotations", [])]
110
+ # Deduplicate
111
+ all_labels = list(dict.fromkeys(labels + objects))
112
+ category = all_labels[0] if all_labels else "Unknown"
113
+ return {"labels": all_labels, "category": category, "source": "google_vision"}
114
+
115
+ def classify_with_clip(image_bytes: bytes) -> dict:
116
+ """Always-free CLIP fallback β€” picks the top 5 matching categories."""
117
+ from PIL import Image as PILImage
118
+ import torch
119
+ model, processor = get_clip()
120
+ image = PILImage.open(io.BytesIO(image_bytes)).convert("RGB")
121
+ inputs = processor(
122
+ text=CLIP_CATEGORIES,
123
+ images=image,
124
+ return_tensors="pt",
125
+ padding=True
126
+ )
127
+ with torch.no_grad():
128
+ outputs = model(**inputs)
129
+ logits = outputs.logits_per_image[0]
130
+ probs = logits.softmax(dim=0)
131
+ top5_idx = probs.topk(5).indices.tolist()
132
+ labels = [CLIP_CATEGORIES[i] for i in top5_idx]
133
+ scores = [round(probs[i].item() * 100, 1) for i in top5_idx]
134
+ return {
135
+ "labels": [f"{l} ({s}%)" for l, s in zip(labels, scores)],
136
+ "category": labels[0],
137
+ "source": "clip_openai"
138
+ }
139
+
140
+ # ── Routes ────────────────────────────────────────────────────────────────────
141
  @app.get("/", tags=["UI"])
142
  async def serve_ui():
143
+ return FileResponse("index.html")
 
 
 
 
144
 
145
  @app.post("/ocr", tags=["OCR"])
146
  async def perform_ocr(
147
  api_key: str = Depends(get_api_key),
148
  file: UploadFile = File(...)
149
  ):
150
+ """Extract text from an image or PDF."""
151
+ contents = await file.read()
152
+ filename = file.filename or ""
 
 
 
 
 
153
  content_type = file.content_type or ""
154
+ is_pdf = content_type == "application/pdf" or filename.lower().endswith(".pdf")
 
155
  is_image = content_type.startswith("image/")
 
156
  if not is_pdf and not is_image:
157
+ raise HTTPException(status_code=400, detail="Upload an image or PDF.")
158
+ try:
159
+ text = process_pdf(contents) if is_pdf else extract_text_from_image_bytes(contents)
160
+ file_type = "pdf" if is_pdf else "image"
161
+ return {"success": True, "filename": filename, "file_type": file_type, "extracted_text": text.strip()}
162
+ except Exception as e:
163
+ raise HTTPException(status_code=500, detail=f"OCR failed: {str(e)}")
164
 
165
+ @app.post("/classify", tags=["Image Classification"])
166
+ async def classify_image(
167
+ api_key: str = Depends(get_api_key),
168
+ file: UploadFile = File(...)
169
+ ):
170
+ """
171
+ Identify the product / category in an image.
172
+ - Tries Google Vision API first (1,000 free requests/month).
173
+ - Automatically falls back to CLIP (100% free, no limits) when Google quota is exhausted.
174
+ """
175
+ if not file.content_type.startswith("image/"):
176
+ raise HTTPException(status_code=400, detail="Please upload an image file.")
177
+ contents = await file.read()
178
  try:
179
+ # β‘  Try Google Vision API
180
+ result = classify_with_google(contents)
181
+ if result:
182
+ return {"success": True, "filename": file.filename, **result}
183
+ # β‘‘ Auto-fallback to CLIP
184
+ result = classify_with_clip(contents)
185
+ return {"success": True, "filename": file.filename, **result}
 
 
 
 
 
 
186
  except Exception as e:
187
+ raise HTTPException(status_code=500, detail=f"Classification failed: {str(e)}")
188
 
189
  if __name__ == "__main__":
190
  import uvicorn
requirements.txt CHANGED
@@ -4,3 +4,7 @@ python-multipart
4
  easyocr
5
  Pillow
6
  pymupdf
 
 
 
 
 
4
  easyocr
5
  Pillow
6
  pymupdf
7
+ transformers
8
+ torch
9
+ torchvision
10
+ google-cloud-vision