| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162 |
- 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 = """
- <html><head><meta charset="utf-8"><title>Résultat OCR Organisé</title>
- <style>
- body { font-family: Arial, sans-serif; background: #f0f0f0; }
- .page {
- position: relative;
- width: 800px; height: 1120px; /* ratio approx A4 */
- margin: 20px auto;
- background: white;
- box-shadow: 0 0 8px rgba(0,0,0,0.2);
- }
- .block {
- position: absolute;
- border: 1px solid rgba(255,0,0,0.5);
- background: rgba(255,255,255,0.7);
- padding: 4px;
- font-size: 14px;
- line-height: 1.2em;
- overflow-wrap: break-word;
- }
- </style>
- </head><body>
- <h1>Résultat OCR Organisé</h1>
- """
- html_body = ""
- for page_idx, page in enumerate(output['pages']):
- html_body += f'<div class="page"><h2>Page {page_idx + 1}</h2>'
- # 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 + "<br>"
- html_body += f'<div class="block" style="left:{left}px; top:{top}px; width:{width}px; height:{height}px;">{block_text}</div>'
- html_body += "</div>" # fin page div
- html_tail = "</body></html>"
- 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 = """
- <html><head><meta charset="utf-8"><title>OCR mots avec bounding boxes</title>
- <style>
- body { font-family: Arial, sans-serif; background: #f0f0f0; }
- .page {
- position: relative;
- width: 800px; height: 1120px; /* ratio A4 approx */
- margin: 20px auto;
- background: white;
- box-shadow: 0 0 8px rgba(0,0,0,0.2);
- }
- .word {
- position: absolute;
- border: 1px solid rgba(0, 0, 255, 0.5);
- background: rgba(255,255,255,0.8);
- font-size: 12px;
- line-height: 1em;
- padding: 1px 2px;
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
- }
- </style>
- </head><body>
- <h1>OCR mots avec bounding boxes</h1>
- """
- html_body = ""
- for page_idx, page in enumerate(output['pages']):
- html_body += f'<div class="page"><h2>Page {page_idx + 1}</h2>'
- 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'<div class="word" style="left:{left}px; top:{top}px; width:{width}px; height:{height}px;">{word_text}</div>'
- html_body += "</div>" # fin page
- html_tail = "</body></html>"
- 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}")
|