import os
import json
from doctr.io import DocumentFile
from doctr.models import ocr_predictor
def load_document(file_path: str):
ext = os.path.splitext(file_path)[-1].lower()
if ext == ".pdf":
return DocumentFile.from_pdf(file_path)
elif ext in [".png", ".jpg", ".jpeg"]:
return DocumentFile.from_images(file_path)
else:
raise ValueError(f"Type de fichier non supporté: {ext}")
def run_ocr(file_path: str):
doc = load_document(file_path)
model = ocr_predictor(pretrained=True)
result = model(doc)
output = result.export()
return doc, output
def generate_html(output, output_html_path="ocr_output.html"):
html_head = """
Page {page_idx + 1}
'
# Pour chaque bloc de texte, positionner la div selon la bounding box normalisée
for block in page['blocks']:
# bbox format: [[x_min, y_min], [x_max, y_max]] (normé 0-1)
(x_min, y_min), (x_max, y_max) = block['geometry']
left = x_min * 800 # correspond à width page
top = y_min * 1120 # correspond à height page
width = (x_max - x_min) * 800
height = (y_max - y_min) * 1120
# Récupérer le texte complet du bloc (concaténation des lignes et mots)
block_text = ""
for line in block['lines']:
line_text = " ".join(word['value'] for word in line['words'])
block_text += line_text + "
"
html_body += f'
{block_text}
'
html_body += "
" # fin page div
html_tail = ""
with open(output_html_path, "w", encoding="utf-8") as f:
f.write(html_head + html_body + html_tail)
print(f"Fichier HTML sauvegardé sous : {output_html_path}")
def extract_text_from_file(file_path: str) -> str:
_, output = run_ocr(file_path)
text = ""
for page in output['pages']:
for block in page['blocks']:
for line in block['lines']:
for word in line['words']:
text += word['value'] + " "
text += "\n"
text += "\n"
text += "\n"
# Sauvegarde du JSON OCR
with open("uploads/ocr_output.json", "w", encoding="utf-8") as fjson:
json.dump(output, fjson, ensure_ascii=False, indent=2)
# Génération HTML
generate_html(output)
return text
def generate_word_level_html(output, output_html_path="uploads/ocr_output_words.html"):
html_head = """
Page {page_idx + 1}
'
for block in page['blocks']:
for line in block['lines']:
for word in line['words']:
# bbox normalized format: [[x_min, y_min], [x_max, y_max]]
(x_min, y_min), (x_max, y_max) = word['geometry']
left = x_min * 800
top = y_min * 1120
width = (x_max - x_min) * 800
height = (y_max - y_min) * 1120
word_text = word['value']
html_body += f'
{word_text}
'
html_body += "
" # fin page
html_tail = ""
with open(output_html_path, "w", encoding="utf-8") as f:
f.write(html_head + html_body + html_tail)
print(f"Fichier HTML mots sauvegardé sous : {output_html_path}")