Nassira commited on
Commit
327e8fb
·
verified ·
1 Parent(s): 5ca489e

Update ocr_extractor.py

Browse files
Files changed (1) hide show
  1. ocr_extractor.py +25 -16
ocr_extractor.py CHANGED
@@ -10,13 +10,13 @@ import paddleocr
10
  from doctr.models import ocr_predictor
11
  from doctr.io import DocumentFile
12
  from collections import defaultdict
 
13
 
14
-
15
-
16
-
17
  aws_access_key_id = os.environ.get('AWS_ACCESS_KEY_ID')
18
  aws_secret_access_key = os.environ.get('AWS_SECRET_ACCESS_KEY')
19
 
 
20
  def load_weights(json_file):
21
  with open(json_file, 'r') as file:
22
  return json.load(file)
@@ -24,8 +24,8 @@ def load_weights(json_file):
24
  def aws_textract(file_path):
25
  client = boto3.client('textract',
26
  region_name='eu-west-3',
27
- aws_access_key_id=os.getenv("aws_access_key_id"),
28
- aws_secret_access_key=os.getenv('aws_secret_access_key'))
29
 
30
  with open(file_path, 'rb') as file:
31
  response = client.detect_document_text(Document={'Bytes': file.read()})
@@ -38,12 +38,12 @@ def doctr_ocr(file_path):
38
  return [(word.value, word.geometry) for block in result.pages for line in block.lines for word in line.words]
39
 
40
  def easyocr_extract(file_path):
41
- reader = easyocr.Reader(['en'])
42
  result = reader.readtext(file_path)
43
  return [(text, bbox) for bbox, text, _ in result]
44
 
45
  def paddleocr_extract(file_path):
46
- ocr = paddleocr.PaddleOCR(use_angle_cls=True, lang='en')
47
  result = ocr.ocr(file_path)
48
  return [(line[1][0], line[0]) for line in result]
49
 
@@ -77,7 +77,7 @@ def weighted_vote(results, weights):
77
  for word, bbox in words:
78
  found_match = False
79
  for existing_word in word_votes:
80
- if calculate_overlap(bbox, existing_word[1]) > 0.5: # 50% de chevauchement
81
  word_votes[existing_word] += weights[method]
82
  found_match = True
83
  break
@@ -87,18 +87,27 @@ def weighted_vote(results, weights):
87
  sorted_words = sorted(word_votes.items(), key=lambda x: (x[1], x[0][1][0], x[0][1][1]), reverse=True)
88
  return [word for (word, _), _ in sorted_words]
89
 
90
- def process_file(file_path, weights_file):
91
  weights = load_weights(weights_file)
92
- if file_path.lower().endswith('.pdf'):
93
- images = pdf2image.convert_from_path(file_path)
 
 
 
 
94
  texts = []
95
  for i, image in enumerate(images):
96
- temp_image_path = f'temp_image_{i}.png'
97
- image.save(temp_image_path, 'PNG')
 
98
  results = {method: extract_text(temp_image_path, method) for method in weights.keys()}
99
  texts.extend(weighted_vote(results, weights))
100
  os.remove(temp_image_path)
101
- return ' '.join(texts)
102
  else:
103
- results = {method: extract_text(file_path, method) for method in weights.keys()}
104
- return ' '.join(weighted_vote(results, weights))
 
 
 
 
 
10
  from doctr.models import ocr_predictor
11
  from doctr.io import DocumentFile
12
  from collections import defaultdict
13
+ import streamlit as st
14
 
15
+ # Charger les variables d'environnement pour AWS
 
 
16
  aws_access_key_id = os.environ.get('AWS_ACCESS_KEY_ID')
17
  aws_secret_access_key = os.environ.get('AWS_SECRET_ACCESS_KEY')
18
 
19
+ @st.cache_data
20
  def load_weights(json_file):
21
  with open(json_file, 'r') as file:
22
  return json.load(file)
 
24
  def aws_textract(file_path):
25
  client = boto3.client('textract',
26
  region_name='eu-west-3',
27
+ aws_access_key_id=aws_access_key_id,
28
+ aws_secret_access_key=aws_secret_access_key)
29
 
30
  with open(file_path, 'rb') as file:
31
  response = client.detect_document_text(Document={'Bytes': file.read()})
 
38
  return [(word.value, word.geometry) for block in result.pages for line in block.lines for word in line.words]
39
 
40
  def easyocr_extract(file_path):
41
+ reader = easyocr.Reader(['all']) # 'all' pour prendre en charge toutes les langues disponibles
42
  result = reader.readtext(file_path)
43
  return [(text, bbox) for bbox, text, _ in result]
44
 
45
  def paddleocr_extract(file_path):
46
+ ocr = paddleocr.PaddleOCR(use_angle_cls=True, lang='ml') # 'ml' pour multilingue
47
  result = ocr.ocr(file_path)
48
  return [(line[1][0], line[0]) for line in result]
49
 
 
77
  for word, bbox in words:
78
  found_match = False
79
  for existing_word in word_votes:
80
+ if calculate_overlap(bbox, existing_word[1]) > 0.5: # 50% overlap
81
  word_votes[existing_word] += weights[method]
82
  found_match = True
83
  break
 
87
  sorted_words = sorted(word_votes.items(), key=lambda x: (x[1], x[0][1][0], x[0][1][1]), reverse=True)
88
  return [word for (word, _), _ in sorted_words]
89
 
90
+ def process_file(file, weights_file):
91
  weights = load_weights(weights_file)
92
+ with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(file.name)[1]) as temp_file:
93
+ temp_file.write(file.getvalue())
94
+ temp_file_path = temp_file.name
95
+
96
+ if file.name.lower().endswith('.pdf'):
97
+ images = pdf2image.convert_from_path(temp_file_path)
98
  texts = []
99
  for i, image in enumerate(images):
100
+ with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as img_temp_file:
101
+ temp_image_path = img_temp_file.name
102
+ image.save(temp_image_path, 'PNG')
103
  results = {method: extract_text(temp_image_path, method) for method in weights.keys()}
104
  texts.extend(weighted_vote(results, weights))
105
  os.remove(temp_image_path)
106
+ extracted_text = ' '.join(texts)
107
  else:
108
+ results = {method: extract_text(temp_file_path, method) for method in weights.keys()}
109
+ extracted_text = ' '.join(weighted_vote(results, weights))
110
+
111
+ os.remove(temp_file_path)
112
+ return extracted_text
113
+