Spaces:
Sleeping
Sleeping
File size: 2,443 Bytes
f871fed |
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 85 86 87 88 89 90 91 92 93 94 95 96 97 |
/**
* OCR Hooks
*
* React Query hooks for image processing and text extraction.
*/
import { useQuery, useMutation } from '@tanstack/react-query';
import { toast } from 'sonner';
import {
processImageBase64,
processImageFile,
getOCRStatus,
fileToBase64,
} from '../api/ocr';
import type { OCRBase64Request } from '../types/ocr';
// Query keys
export const ocrKeys = {
all: ['ocr'] as const,
status: () => [...ocrKeys.all, 'status'] as const,
};
/**
* Hook to check OCR service status
*/
export function useOCRStatus() {
return useQuery({
queryKey: ocrKeys.status(),
queryFn: getOCRStatus,
staleTime: 60000, // 1 minute
});
}
/**
* Hook to process image with base64 encoding
*/
export function useProcessImageBase64() {
return useMutation({
mutationFn: (data: OCRBase64Request) => processImageBase64(data),
onSuccess: () => {
toast.success('Image processed successfully');
},
onError: (error: Error) => {
toast.error(`OCR processing failed: ${error.message}`);
},
});
}
/**
* Hook to process uploaded image file
*/
export function useProcessImageFile() {
return useMutation({
mutationFn: ({ file, structure = true }: { file: File; structure?: boolean }) =>
processImageFile(file, structure),
onSuccess: () => {
toast.success('Image processed successfully');
},
onError: (error: Error) => {
toast.error(`OCR processing failed: ${error.message}`);
},
});
}
/**
* Hook that handles file selection and processing
*/
export function useOCRProcessor() {
const processMutation = useProcessImageFile();
const processFile = async (file: File, structure: boolean = true) => {
// Validate file type
const validTypes = ['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/webp', 'image/bmp'];
if (!validTypes.includes(file.type)) {
toast.error('Invalid file type. Please upload an image (PNG, JPEG, GIF, WebP, or BMP).');
return null;
}
// Validate file size (max 10MB)
const maxSize = 10 * 1024 * 1024;
if (file.size > maxSize) {
toast.error('File too large. Maximum size is 10MB.');
return null;
}
return processMutation.mutateAsync({ file, structure });
};
return {
processFile,
isProcessing: processMutation.isPending,
result: processMutation.data,
error: processMutation.error,
reset: processMutation.reset,
};
}
|