Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .docker/php-fpm/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
libxslt1-dev \
libicu-dev \
libpq-dev \
tesseract-ocr \
tesseract-ocr-fra \
Comment on lines +17 to +18

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tesseract + Version de détection des texte en français

poppler-utils \

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Permet de récupérer directement les texte des PDF qui ne sont pas des scan.
Permet aussi de convertir les PDF en image afind e pouvoir appliquer le traitement OCR de tesseract dessus (qui n'accepte pas les format PDF en entrée)

&& curl -fsSL https://deb.nodesource.com/setup_24.x | bash \
&& apt-get install -y nodejs \
# Install intl
Expand Down
3 changes: 3 additions & 0 deletions Aptfile
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
bsdextrautils
tesseract-ocr
tesseract-ocr-fra
poppler-utils
94 changes: 94 additions & 0 deletions src/Controller/Back/TesseractToolController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
<?php

namespace App\Controller\Back;

use App\Form\TesseractType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;

#[Route('/bo/tools/document-extractor')]
#[IsGranted('ROLE_ADMIN')]
class TesseractToolController extends AbstractController
{
private const int PDF_TEXT_MIN_LENGTH = 100;

#[Route('/', name: 'back_tools_document_extractor', methods: ['GET', 'POST'])]
public function index(
Request $request,
): Response {
$form = $this->createForm(TesseractType::class);
$form->handleRequest($request);
$text = null;

if ($form->isSubmitted() && $form->isValid()) {
/** @var UploadedFile $file */
$file = $form->get('file')->getData();
try {
$text = $this->extractText($file);
} catch (ProcessFailedException $e) {
$this->addFlash('error', 'Erreur lors de l\'analyse : '.$e->getProcess()->getErrorOutput());
}
}

return $this->render('back/tools/document-extractor.html.twig', [
'form' => $form,
'text' => $text,
]);
}

private function extractText(UploadedFile $file): string
{
// pour les images on passe toujours par l'OCR de tesseract
if ('application/pdf' !== $file->getMimeType()) {
return trim($this->run(['tesseract', $file->getPathname(), 'stdout', '-l', 'fra']));
}

// pour les PDF on essaie d'abord d'extraire le texte directement (pdftotext)
$pdfPath = $file->getPathname();
$pdfText = trim($this->run(['pdftotext', $pdfPath, '-']));
$meaningfulLength = mb_strlen(preg_replace('/\s+/', '', $pdfText) ?? '');
// on considére que le PDF est au format texte si le texte contient plus de 100 caractères significatifs
if ($meaningfulLength >= self::PDF_TEXT_MIN_LENGTH) {
return $pdfText;
}

// sinon on bascule sur la transformation des page du PDF en image (pdftoppm) pour pouvoir leur appliquer le traitement OCR de tesseract
$filesystem = new Filesystem();
$tmpDir = $filesystem->tempnam(sys_get_temp_dir(), 'ocr_');
$filesystem->remove($tmpDir);
$filesystem->mkdir($tmpDir);

try {
$this->run(['pdftoppm', '-r', '300', '-png', $pdfPath, $tmpDir.'/page']);
$images = glob($tmpDir.'/page*.png') ?: [];
sort($images);

$text = '';
foreach ($images as $image) {
$text .= $this->run(['tesseract', $image, 'stdout', '-l', 'fra'])."\n";
}

return trim($text);
} finally {
$filesystem->remove($tmpDir);
}
}

/**
* @param array<int, string> $command
*/
private function run(array $command): string
{
$process = new Process($command);
$process->mustRun();

return $process->getOutput();
}
}
42 changes: 42 additions & 0 deletions src/Form/TesseractType.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

namespace App\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints as Assert;

/**
* @extends AbstractType<mixed>
*/
class TesseractType extends AbstractType
{
/**
* @param array<string, mixed> $options
*/
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('file', FileType::class, [
'label' => 'Fichier à analyser',
'required' => true,
'help' => 'Extensions acceptées : PDF, JPG ou PNG (max 25 Mo)',
'constraints' => [
new Assert\File(
maxSize : '25M',
mimeTypes : [
'application/pdf',
'image/jpeg',
'image/png',
],
mimeTypesMessage : 'Veuillez télécharger un fichier PDF, JPG ou PNG valide',
),
],
])
->add('submit', SubmitType::class, [
'label' => 'Analyser',
]);
}
}
1 change: 1 addition & 0 deletions src/Service/Menu/MenuBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ public function build(): MenuItem
->addChild(new MenuItem(label: 'Historique des modifications', route: 'back_history_entry_diff', roleGranted: User::ROLE_ADMIN))
->addChild(new MenuItem(label: 'Outil RIAL par BAN ID', route: 'back_tools_rial', roleGranted: User::ROLE_ADMIN))
->addChild(new MenuItem(label: 'Outil Document IA', route: 'back_tools_document_ia', roleGranted: User::ROLE_ADMIN))
->addChild(new MenuItem(label: 'Outil OCR (Tesseract)', route: 'back_tools_document_extractor', roleGranted: User::ROLE_ADMIN))
;
$techAdminToolsSubItem
->addChild(new MenuItem(route: 'back_territories_edit'))
Expand Down
33 changes: 33 additions & 0 deletions templates/back/tools/document-extractor.html.twig
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
{% extends 'back/base_bo.html.twig' %}

{% block title %}Outil OCR (Tesseract){% endblock %}

{% block content %}
<section class="fr-p-5v">
{% include 'back/breadcrumb_bo.html.twig' with {
'level2Title': 'Outils SA',
'level2Link': '',
'level2Label': '',
'level3Title': 'Outil OCR (Tesseract)',
'level3Link': '',
} %}
<header>
<div class="fr-grid-row">
<div class="fr-col-12">
<h1>Outil OCR (Tesseract)</h1>
</div>
</div>
</header>
</section>

<section class="fr-col-12 fr-p-5v">
<div class="fr-mb-4v">
{{form(form)}}
</div>
{% if text is not null %}
<h2>Texte extrait</h2>
<pre class="fr-p-2v" style="white-space: pre-wrap;">{{ text }}</pre>
{% endif %}
</section>

{% endblock %}
Loading