import { NextResponse, type NextRequest } from "next/server"; import pdf from "pdf-parse"; // ✅ Import correct 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 --- 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); // ✅ Vérification supplémentaire if (!fileContent.trim()) { console.log("⚠️ PDF vide ou non lisible"); return NextResponse.json( { error: "Le PDF ne contient pas de texte extractible ou est protégé." }, { status: 400 } ); } } catch (pdfError) { console.error("❌ Erreur PDF détaillée:", pdfError); return NextResponse.json( { error: `Erreur traitement PDF: ${pdfError instanceof Error ? pdfError.message : "Erreur inconnue"}. Vérifiez que le PDF n'est pas protégé ou corrompu.`, }, { 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) { console.error("❌ Erreur Word:", 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) { console.error("❌ Erreur texte:", 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 } ); } // Vérifier si c'est juste pour l'extraction de texte (lecture simple) const isSimpleExtraction = req.headers.get("x-simple-extraction") === "true"; if (isSimpleExtraction) { // Retourner juste le texte extrait return NextResponse.json({ text: fileContent }, { status: 200 }); } // ========================================================== // CONFIGURATION PRESIDIO ANALYZER (pour l'anonymisation complète) // ========================================================== const analyzerConfig = { text: fileContent, language: "fr", }; console.log("🔍 Appel à Presidio Analyzer..."); // ✅ Définir l'URL AVANT de l'utiliser const presidioAnalyzerUrl = "http://analyzer.151.80.20.211.sslip.io/analyze"; try { 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); console.log("📊 Headers Analyzer:", analyzeResponse.headers); if (!analyzeResponse.ok) { const errorBody = await analyzeResponse.text(); console.error("❌ Erreur Analyzer:", errorBody); console.error("❌ URL utilisée:", presidioAnalyzerUrl); console.error("❌ Config envoyée:", analyzerConfig); // Fallback: retourner juste le texte si Presidio n'est pas disponible return NextResponse.json({ text: fileContent }, { status: 200 }); } const analyzerResults = await analyzeResponse.json(); console.log("✅ Analyzer a trouvé", analyzerResults.length, "entités."); // ========================================================================= // CONFIGURATION PRESIDIO ANONYMIZER // ========================================================================= 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(); console.error("❌ Erreur Anonymizer:", errorBody); // Fallback: retourner juste le texte si Presidio n'est pas disponible return NextResponse.json({ text: fileContent }, { status: 200 }); } const anonymizerResult = await anonymizeResponse.json(); console.log("✅ Anonymisation réussie."); const result = { text: fileContent, anonymizedText: anonymizerResult.text, piiCount: analyzerResults.length, analyzerResults: analyzerResults, }; return NextResponse.json(result, { status: 200 }); } catch (presidioError) { console.error("❌ Erreur Presidio:", presidioError); // Fallback: retourner juste le texte extrait return NextResponse.json({ text: fileContent }, { 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 } ); } }