Files
Anonyme/app/api/process-document/route.ts
2025-07-25 17:59:35 +02:00

181 lines
5.7 KiB
TypeScript

import { NextResponse, type NextRequest } from "next/server";
import pdf from "pdf-parse/lib/pdf-parse";
import mammoth from "mammoth";
export async function POST(req: NextRequest) {
console.log("🔍 Début du traitement de la requête");
try {
const formData = await req.formData();
const file = formData.get("file") as File | null;
if (!file) {
return NextResponse.json(
{ error: "Aucun fichier reçu." },
{ status: 400 }
);
}
console.log("📁 Fichier reçu:", file.name, "| Type:", file.type);
let fileContent = "";
const fileType = file.type;
// --- LOGIQUE D'EXTRACTION DE TEXTE (INCHANGÉE) ---
if (fileType === "application/pdf") {
console.log("📄 Traitement PDF en cours...");
try {
const buffer = Buffer.from(await file.arrayBuffer());
const data = await pdf(buffer);
fileContent = data.text;
console.log("✅ Extraction PDF réussie, longueur:", fileContent.length);
} catch (pdfError) {
return NextResponse.json(
{
error: `Erreur traitement PDF: ${
pdfError instanceof Error ? pdfError.message : "Erreur inconnue"
}`,
},
{ status: 500 }
);
}
} else if (
fileType ===
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"
) {
console.log("📝 Traitement Word en cours...");
try {
const arrayBuffer = await file.arrayBuffer();
const result = await mammoth.extractRawText({ arrayBuffer });
fileContent = result.value;
console.log(
"✅ Extraction Word réussie, longueur:",
fileContent.length
);
} catch (wordError) {
return NextResponse.json(
{
error: `Erreur traitement Word: ${
wordError instanceof Error ? wordError.message : "Erreur inconnue"
}`,
},
{ status: 500 }
);
}
} else {
console.log("📄 Traitement texte en cours...");
try {
fileContent = await file.text();
console.log(
"✅ Extraction texte réussie, longueur:",
fileContent.length
);
} catch (textError) {
return NextResponse.json(
{
error: `Erreur lecture texte: ${
textError instanceof Error ? textError.message : "Erreur inconnue"
}`,
},
{ status: 500 }
);
}
}
if (!fileContent || fileContent.trim().length === 0) {
console.log("⚠️ Contenu vide détecté");
return NextResponse.json(
{ error: "Le fichier ne contient pas de texte extractible." },
{ status: 400 }
);
}
// ======================================================================
// CONFIGURATION PRESIDIO ANALYZER (SIMPLIFIÉE)
// ======================================================================
// Toute la configuration (recognizers, allow_list, etc.) est maintenant dans le default.yaml du service.
// L'API a juste besoin d'envoyer le texte et la langue.
const analyzerConfig = {
text: fileContent,
language: "fr",
};
console.log("🔍 Appel à Presidio Analyzer...");
const presidioAnalyzerUrl =
"http://analyzer.151.80.20.211.sslip.io/analyze";
const analyzeResponse = await fetch(presidioAnalyzerUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify(analyzerConfig),
});
console.log("📊 Statut Analyzer:", analyzeResponse.status);
if (!analyzeResponse.ok) {
const errorBody = await analyzeResponse.text();
return NextResponse.json(
{ error: `Erreur Analyzer: ${errorBody}` },
{ status: 500 }
);
}
const analyzerResults = await analyzeResponse.json();
console.log("✅ Analyzer a trouvé", analyzerResults.length, "entités.");
// =========================================================================
// CONFIGURATION PRESIDIO ANONYMIZER
// =========================================================================
// L'Anonymizer lira la config d'anonymisation du default.yaml de l'Analyzer
// ou vous pouvez définir des transformations spécifiques ici si besoin.
// Pour commencer, on envoie juste les résultats de l'analyse.
const anonymizerConfig = {
text: fileContent,
analyzer_results: analyzerResults,
};
console.log("🔍 Appel à Presidio Anonymizer...");
const presidioAnonymizerUrl =
"http://anonymizer.151.80.20.211.sslip.io/anonymize";
const anonymizeResponse = await fetch(presidioAnonymizerUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify(anonymizerConfig),
});
console.log("📊 Statut Anonymizer:", anonymizeResponse.status);
if (!anonymizeResponse.ok) {
const errorBody = await anonymizeResponse.text();
return NextResponse.json(
{ error: `Erreur Anonymizer: ${errorBody}` },
{ status: 500 }
);
}
const anonymizerResult = await anonymizeResponse.json();
console.log("✅ Anonymisation réussie.");
const result = {
anonymizedText: anonymizerResult.text,
piiCount: analyzerResults.length,
};
return NextResponse.json(result, { status: 200 });
} catch (err: unknown) {
console.error("❌ Erreur générale:", err);
return NextResponse.json(
{
error: err instanceof Error ? err.message : "Erreur serveur inconnue.",
},
{ status: 500 }
);
}
}