feat(documents): Integrate client-side processing into upload form

- Updated DocumentUploadForm to use processDocument utility
- Added real-time progress tracking with visual feedback
- Display extracted text in editable textarea
- Support compressed file upload
- Added extracted_text field to API client and backend serializer
- Auto-process PDFs, DOCX, and images on file selection
This commit is contained in:
igor_nadein 2026-02-28 09:36:17 +03:00
parent 047e1c1763
commit a315ce4f33
3 changed files with 150 additions and 24 deletions

View File

@ -278,6 +278,7 @@ class DocumentWriteSerializer(serializers.ModelSerializer):
"title",
"description",
"file",
"extracted_text",
"sent_to_all",
"department_ids",
"recipient_ids",

View File

@ -2,28 +2,86 @@
import { useState, useCallback } from "react";
import { useDropzone } from "react-dropzone";
import { Upload, X, FileText, AlertCircle } from "lucide-react";
import { Upload, X, FileText, AlertCircle, Loader2 } from "lucide-react";
import { apiClient } from "@/lib/api";
import { toast } from "sonner";
import { processDocument, needsProcessing, type ProcessingProgress } from "@/lib/document-utils";
interface DocumentUploadFormProps {
onSuccess?: () => void;
onCancel?: () => void;
}
// Сообщения для различных этапов обработки
const STAGE_MESSAGES: Record<string, string> = {
compressing: "Сжатие изображения...",
ocr: "Распознавание текста (OCR)...",
extracting_text: "Извлечение текста...",
generating_thumbnail: "Создание миниатюры...",
complete: "Обработка завершена",
};
export function DocumentUploadForm({ onSuccess, onCancel }: DocumentUploadFormProps) {
const [title, setTitle] = useState("");
const [description, setDescription] = useState("");
const [file, setFile] = useState<File | null>(null);
const [processedFile, setProcessedFile] = useState<File | Blob | null>(null);
const [extractedText, setExtractedText] = useState("");
const [isProcessing, setIsProcessing] = useState(false);
const [processingProgress, setProcessingProgress] = useState<ProcessingProgress | null>(null);
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
const onDrop = useCallback((acceptedFiles: File[]) => {
const onDrop = useCallback(async (acceptedFiles: File[]) => {
if (acceptedFiles.length > 0) {
setFile(acceptedFiles[0]);
const selectedFile = acceptedFiles[0];
setFile(selectedFile);
setError(null);
// Автоматически заполняем название, если оно пустое
if (!title && acceptedFiles[0].name) {
setTitle(acceptedFiles[0].name.replace(/\.[^/.]+$/, "")); // Убираем расширение
if (!title && selectedFile.name) {
setTitle(selectedFile.name.replace(/\.[^/.]+$/, "")); // Убираем расширение
}
// Проверяем, требуется ли обработка файла
if (needsProcessing(selectedFile)) {
setIsProcessing(true);
setProcessingProgress({
stage: "compressing",
progress: 0,
message: "Начало обработки..."
});
try {
const result = await processDocument(selectedFile, {
enableOCR: true,
enableCompression: true,
enableTextExtraction: true,
enableThumbnail: true,
onProgress: (progress) => {
setProcessingProgress(progress);
},
});
// Сохраняем извлеченный текст
if (result.extractedText) {
setExtractedText(result.extractedText);
}
// Если файл был обработан (сжат), используем обработанную версию
if (result.processedFile) {
setProcessedFile(result.processedFile);
}
toast.success("Документ обработан успешно");
} catch (err) {
console.error("Ошибка обработки документа:", err);
setError(err instanceof Error ? err.message : "Не удалось обработать документ");
toast.error("Ошибка обработки документа");
} finally {
setIsProcessing(false);
setProcessingProgress(null);
}
}
}
}, [title]);
@ -54,10 +112,14 @@ export function DocumentUploadForm({ onSuccess, onCancel }: DocumentUploadFormPr
setIsSubmitting(true);
try {
// Используем обработанный файл, если он есть, иначе оригинальный
const fileToUpload = processedFile || file;
await apiClient.createDocument({
title,
description,
file,
file: fileToUpload,
extracted_text: extractedText || undefined, // Отправляем извлеченный текст, если есть
});
toast.success("Документ успешно загружен");
@ -66,6 +128,8 @@ export function DocumentUploadForm({ onSuccess, onCancel }: DocumentUploadFormPr
setTitle("");
setDescription("");
setFile(null);
setProcessedFile(null);
setExtractedText("");
if (onSuccess) {
onSuccess();
@ -113,21 +177,56 @@ export function DocumentUploadForm({ onSuccess, onCancel }: DocumentUploadFormPr
</p>
</div>
) : (
<div className="flex items-center gap-3 rounded-lg border border-gray-200 bg-white p-3">
<FileText size={20} className="shrink-0 text-sky-600" />
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium text-gray-900">{file.name}</p>
<p className="text-xs text-gray-500">
{(file.size / 1024 / 1024).toFixed(2)} МБ
</p>
<div className="space-y-3">
<div className="flex items-center gap-3 rounded-lg border border-gray-200 bg-white p-3">
<FileText size={20} className="shrink-0 text-sky-600" />
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium text-gray-900">{file.name}</p>
<p className="text-xs text-gray-500">
{(file.size / 1024 / 1024).toFixed(2)} МБ
</p>
</div>
<button
type="button"
onClick={() => {
setFile(null);
setProcessedFile(null);
setExtractedText("");
}}
disabled={isProcessing}
className="shrink-0 rounded-full p-1 text-gray-400 hover:bg-gray-100 hover:text-gray-600 disabled:cursor-not-allowed disabled:opacity-50"
>
<X size={16} />
</button>
</div>
<button
type="button"
onClick={() => setFile(null)}
className="shrink-0 rounded-full p-1 text-gray-400 hover:bg-gray-100 hover:text-gray-600"
>
<X size={16} />
</button>
{/* Индикатор обработки */}
{isProcessing && processingProgress && (
<div className="rounded-lg border border-sky-200 bg-sky-50 p-3">
<div className="flex items-center gap-2 mb-2">
<Loader2 size={16} className="animate-spin text-sky-600" />
<span className="text-sm font-medium text-sky-900">
{STAGE_MESSAGES[processingProgress.stage] || "Обработка..."}
</span>
</div>
<div className="h-2 bg-sky-200 rounded-full overflow-hidden">
<div
className="h-full bg-sky-600 transition-all duration-300"
style={{ width: `${processingProgress.progress}%` }}
/>
</div>
<p className="text-xs text-sky-700 mt-1">
{processingProgress.progress}%
</p>
</div>
)}
{/* Сообщение о сжатии */}
{processedFile && !isProcessing && (
<div className="rounded-lg border border-green-200 bg-green-50 p-2 text-xs text-green-800">
✓ Изображение сжато: {(file.size / 1024 / 1024).toFixed(2)} МБ → {(processedFile.size / 1024 / 1024).toFixed(2)} МБ
</div>
)}
</div>
)}
</div>
@ -163,21 +262,45 @@ export function DocumentUploadForm({ onSuccess, onCancel }: DocumentUploadFormPr
/>
</div>
{/* Извлеченный текст */}
{extractedText && (
<div>
<label htmlFor="extractedText" className="mb-1.5 block text-sm font-medium text-gray-700">
Извлеченный текст
<span className="ml-1 text-xs font-normal text-gray-500">
(будет использован для поиска, можно отредактировать)
</span>
</label>
<textarea
id="extractedText"
value={extractedText}
onChange={(e) => setExtractedText(e.target.value)}
placeholder="Текст, извлеченный из документа"
rows={5}
className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm font-mono focus:border-sky-500 focus:outline-none focus:ring-2 focus:ring-sky-100"
/>
<p className="mt-1 text-xs text-gray-500">
Символов: {extractedText.length}
</p>
</div>
)}
{/* Buttons */}
<div className="flex gap-3">
<button
type="submit"
disabled={isSubmitting || !title || !file}
disabled={isSubmitting || isProcessing || !title || !file}
className="flex-1 rounded-lg bg-sky-600 px-4 py-2.5 text-sm font-medium text-white transition hover:bg-sky-700 disabled:cursor-not-allowed disabled:opacity-50"
>
{isSubmitting ? "Загрузка..." : "Загрузить документ"}
{isSubmitting ? "Загрузка..." : isProcessing ? "Обработка..." : "Загрузить документ"}
</button>
{onCancel && (
<button
type="button"
onClick={onCancel}
className="rounded-lg border border-gray-300 px-4 py-2.5 text-sm font-medium text-gray-700 transition hover:bg-gray-50"
disabled={isProcessing}
className="rounded-lg border border-gray-300 px-4 py-2.5 text-sm font-medium text-gray-700 transition hover:bg-gray-50 disabled:cursor-not-allowed disabled:opacity-50"
>
Отмена
</button>

View File

@ -302,11 +302,13 @@ class ApiClient {
async createDocument(data: {
title: string;
description?: string;
file: File;
file: File | Blob;
extracted_text?: string;
}): Promise<any> {
const formData = new FormData();
formData.append('title', data.title);
if (data.description) formData.append('description', data.description);
if (data.extracted_text) formData.append('extracted_text', data.extracted_text);
formData.append('file', data.file);
return this.request('/api/v1/documents/', {