ocr.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. import os
  2. import json
  3. from doctr.io import DocumentFile
  4. from doctr.models import ocr_predictor
  5. def load_document(file_path: str):
  6. ext = os.path.splitext(file_path)[-1].lower()
  7. if ext == ".pdf":
  8. return DocumentFile.from_pdf(file_path)
  9. elif ext in [".png", ".jpg", ".jpeg"]:
  10. return DocumentFile.from_images(file_path)
  11. else:
  12. raise ValueError(f"Type de fichier non supporté: {ext}")
  13. def run_ocr(file_path: str):
  14. doc = load_document(file_path)
  15. model = ocr_predictor(pretrained=True)
  16. result = model(doc)
  17. output = result.export()
  18. return doc, output
  19. def generate_html(output, output_html_path="ocr_output.html"):
  20. html_head = """
  21. <html><head><meta charset="utf-8"><title>Résultat OCR Organisé</title>
  22. <style>
  23. body { font-family: Arial, sans-serif; background: #f0f0f0; }
  24. .page {
  25. position: relative;
  26. width: 800px; height: 1120px; /* ratio approx A4 */
  27. margin: 20px auto;
  28. background: white;
  29. box-shadow: 0 0 8px rgba(0,0,0,0.2);
  30. }
  31. .block {
  32. position: absolute;
  33. border: 1px solid rgba(255,0,0,0.5);
  34. background: rgba(255,255,255,0.7);
  35. padding: 4px;
  36. font-size: 14px;
  37. line-height: 1.2em;
  38. overflow-wrap: break-word;
  39. }
  40. </style>
  41. </head><body>
  42. <h1>Résultat OCR Organisé</h1>
  43. """
  44. html_body = ""
  45. for page_idx, page in enumerate(output['pages']):
  46. html_body += f'<div class="page"><h2>Page {page_idx + 1}</h2>'
  47. # Pour chaque bloc de texte, positionner la div selon la bounding box normalisée
  48. for block in page['blocks']:
  49. # bbox format: [[x_min, y_min], [x_max, y_max]] (normé 0-1)
  50. (x_min, y_min), (x_max, y_max) = block['geometry']
  51. left = x_min * 800 # correspond à width page
  52. top = y_min * 1120 # correspond à height page
  53. width = (x_max - x_min) * 800
  54. height = (y_max - y_min) * 1120
  55. # Récupérer le texte complet du bloc (concaténation des lignes et mots)
  56. block_text = ""
  57. for line in block['lines']:
  58. line_text = " ".join(word['value'] for word in line['words'])
  59. block_text += line_text + "<br>"
  60. html_body += f'<div class="block" style="left:{left}px; top:{top}px; width:{width}px; height:{height}px;">{block_text}</div>'
  61. html_body += "</div>" # fin page div
  62. html_tail = "</body></html>"
  63. with open(output_html_path, "w", encoding="utf-8") as f:
  64. f.write(html_head + html_body + html_tail)
  65. print(f"Fichier HTML sauvegardé sous : {output_html_path}")
  66. def extract_text_from_file(file_path: str) -> str:
  67. _, output = run_ocr(file_path)
  68. text = ""
  69. for page in output['pages']:
  70. for block in page['blocks']:
  71. for line in block['lines']:
  72. for word in line['words']:
  73. text += word['value'] + " "
  74. text += "\n"
  75. text += "\n"
  76. text += "\n"
  77. # Sauvegarde du JSON OCR
  78. with open("uploads/ocr_output.json", "w", encoding="utf-8") as fjson:
  79. json.dump(output, fjson, ensure_ascii=False, indent=2)
  80. # Génération HTML
  81. generate_html(output)
  82. return text
  83. def generate_word_level_html(output, output_html_path="uploads/ocr_output_words.html"):
  84. html_head = """
  85. <html><head><meta charset="utf-8"><title>OCR mots avec bounding boxes</title>
  86. <style>
  87. body { font-family: Arial, sans-serif; background: #f0f0f0; }
  88. .page {
  89. position: relative;
  90. width: 800px; height: 1120px; /* ratio A4 approx */
  91. margin: 20px auto;
  92. background: white;
  93. box-shadow: 0 0 8px rgba(0,0,0,0.2);
  94. }
  95. .word {
  96. position: absolute;
  97. border: 1px solid rgba(0, 0, 255, 0.5);
  98. background: rgba(255,255,255,0.8);
  99. font-size: 12px;
  100. line-height: 1em;
  101. padding: 1px 2px;
  102. white-space: nowrap;
  103. overflow: hidden;
  104. text-overflow: ellipsis;
  105. }
  106. </style>
  107. </head><body>
  108. <h1>OCR mots avec bounding boxes</h1>
  109. """
  110. html_body = ""
  111. for page_idx, page in enumerate(output['pages']):
  112. html_body += f'<div class="page"><h2>Page {page_idx + 1}</h2>'
  113. for block in page['blocks']:
  114. for line in block['lines']:
  115. for word in line['words']:
  116. # bbox normalized format: [[x_min, y_min], [x_max, y_max]]
  117. (x_min, y_min), (x_max, y_max) = word['geometry']
  118. left = x_min * 800
  119. top = y_min * 1120
  120. width = (x_max - x_min) * 800
  121. height = (y_max - y_min) * 1120
  122. word_text = word['value']
  123. html_body += f'<div class="word" style="left:{left}px; top:{top}px; width:{width}px; height:{height}px;">{word_text}</div>'
  124. html_body += "</div>" # fin page
  125. html_tail = "</body></html>"
  126. with open(output_html_path, "w", encoding="utf-8") as f:
  127. f.write(html_head + html_body + html_tail)
  128. print(f"Fichier HTML mots sauvegardé sous : {output_html_path}")