Nassira commited on
Commit
aebc0eb
·
verified ·
1 Parent(s): 0203830

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -65
app.py CHANGED
@@ -2,8 +2,8 @@ import os
2
  import time
3
  from doctr.models import ocr_predictor
4
  from doctr.io import DocumentFile
5
- import re
6
- from collections import Counter
7
 
8
  # Initialize doctr OCR model
9
  ocr_model = ocr_predictor(pretrained=True)
@@ -11,31 +11,23 @@ ocr_model = ocr_predictor(pretrained=True)
11
  def extract_text_from_image(image_path):
12
  doc = DocumentFile.from_images(image_path)
13
  result = ocr_model(doc)
14
- extracted_text = []
15
- for page in result.pages:
16
- for block in page.blocks:
17
- for line in block.lines:
18
- for word in line.words:
19
- extracted_text.append(word.value)
20
- return ' '.join(extracted_text)
21
 
22
  def read_text_file(file_path):
23
  with open(file_path, 'r', encoding='utf-8') as file:
24
  return file.read()
25
 
26
  def preprocess_text(text):
27
- # Convert to lowercase and remove punctuation
28
- text = re.sub(r'[^\w\s]', '', text.lower())
29
- # Split into words
30
- return text.split()
31
 
32
  def calculate_metrics(extracted_text, reference_text):
33
- extracted_words = Counter(preprocess_text(extracted_text))
34
- reference_words = Counter(preprocess_text(reference_text))
35
 
36
- true_positives = sum((extracted_words & reference_words).values())
37
- false_positives = sum((extracted_words - reference_words).values())
38
- false_negatives = sum((reference_words - extracted_words).values())
39
 
40
  precision = true_positives / (true_positives + false_positives) if (true_positives + false_positives) > 0 else 0
41
  recall = true_positives / (true_positives + false_negatives) if (true_positives + false_negatives) > 0 else 0
@@ -43,53 +35,47 @@ def calculate_metrics(extracted_text, reference_text):
43
 
44
  return precision, recall, f1_score
45
 
46
- # Directories containing the images and text files
47
- image_dir = r'C:\Users\PC\Desktop\CapitalTech\talentino-cv-quality\Images CV'
48
- text_dir = r'C:\Users\PC\Desktop\CapitalTech\talentino-cv-quality\ground_truth'
49
 
50
- total_precision = 0.0
51
- total_recall = 0.0
52
- total_f1 = 0.0
53
- num_files = 0
54
- total_execution_time = 0.0
55
-
56
- for image_filename in os.listdir(image_dir):
57
- if image_filename.endswith('.png'):
58
- image_path = os.path.join(image_dir, image_filename)
59
- text_file_path = os.path.join(text_dir, image_filename.replace('.png', '.txt'))
60
-
61
- if os.path.exists(text_file_path):
62
- start_time = time.time()
63
-
64
- extracted_text = extract_text_from_image(image_path)
65
- pre_existing_text = read_text_file(text_file_path)
66
-
67
- precision, recall, f1_score = calculate_metrics(extracted_text, pre_existing_text)
68
-
69
- total_precision += precision
70
- total_recall += recall
71
- total_f1 += f1_score
72
- num_files += 1
73
-
74
- execution_time = time.time() - start_time
75
- total_execution_time += execution_time
76
 
77
- print(f"File: {image_filename}")
78
- print(f"Precision: {precision:.2f}")
79
- print(f"Recall: {recall:.2f}")
80
- print(f"F1 Score: {f1_score:.2f}")
81
- print(f"Execution Time: {execution_time:.2f} seconds\n")
82
- else:
83
- print(f"Text file not found for image: {image_filename}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
 
85
- if num_files > 0:
86
- average_precision = total_precision / num_files
87
- average_recall = total_recall / num_files
88
- average_f1 = total_f1 / num_files
89
- average_execution_time = total_execution_time / num_files
90
- print(f"\nAverage Precision: {average_precision:.2f}")
91
- print(f"Average Recall: {average_recall:.2f}")
92
- print(f"Average F1 Score: {average_f1:.2f}")
93
- print(f"Average Execution Time: {average_execution_time:.2f} seconds per file")
94
- else:
95
- print("No matching text files found for any images.")
 
2
  import time
3
  from doctr.models import ocr_predictor
4
  from doctr.io import DocumentFile
5
+ from sklearn.metrics import precision_recall_fscore_support
6
+ import numpy as np
7
 
8
  # Initialize doctr OCR model
9
  ocr_model = ocr_predictor(pretrained=True)
 
11
  def extract_text_from_image(image_path):
12
  doc = DocumentFile.from_images(image_path)
13
  result = ocr_model(doc)
14
+ return ' '.join(word.value for page in result.pages for block in page.blocks for line in block.lines for word in line.words)
 
 
 
 
 
 
15
 
16
  def read_text_file(file_path):
17
  with open(file_path, 'r', encoding='utf-8') as file:
18
  return file.read()
19
 
20
  def preprocess_text(text):
21
+ # Convert to lowercase and split into words
22
+ return set(text.lower().split())
 
 
23
 
24
  def calculate_metrics(extracted_text, reference_text):
25
+ extracted_words = preprocess_text(extracted_text)
26
+ reference_words = preprocess_text(reference_text)
27
 
28
+ true_positives = len(extracted_words.intersection(reference_words))
29
+ false_positives = len(extracted_words - reference_words)
30
+ false_negatives = len(reference_words - extracted_words)
31
 
32
  precision = true_positives / (true_positives + false_positives) if (true_positives + false_positives) > 0 else 0
33
  recall = true_positives / (true_positives + false_negatives) if (true_positives + false_negatives) > 0 else 0
 
35
 
36
  return precision, recall, f1_score
37
 
38
+ def process_files(image_dir, text_dir):
39
+ metrics = []
40
+ execution_times = []
41
 
42
+ for image_filename in os.listdir(image_dir):
43
+ if image_filename.endswith('.png'):
44
+ image_path = os.path.join(image_dir, image_filename)
45
+ text_file_path = os.path.join(text_dir, image_filename.replace('.png', '.txt'))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
 
47
+ if os.path.exists(text_file_path):
48
+ start_time = time.time()
49
+
50
+ extracted_text = extract_text_from_image(image_path)
51
+ pre_existing_text = read_text_file(text_file_path)
52
+
53
+ precision, recall, f1_score = calculate_metrics(extracted_text, pre_existing_text)
54
+ metrics.append((precision, recall, f1_score))
55
+
56
+ execution_time = time.time() - start_time
57
+ execution_times.append(execution_time)
58
+ else:
59
+ print(f"Text file not found for image: {image_filename}")
60
+
61
+ return metrics, execution_times
62
+
63
+ def main():
64
+ image_dir = 'Images CV'
65
+ text_dir = 'ground_truth'
66
+
67
+ metrics, execution_times = process_files(image_dir, text_dir)
68
+
69
+ if metrics:
70
+ avg_precision, avg_recall, avg_f1 = np.mean(metrics, axis=0)
71
+ avg_execution_time = np.mean(execution_times)
72
+
73
+ print(f"\nAverage Precision: {avg_precision:.2f}")
74
+ print(f"Average Recall: {avg_recall:.2f}")
75
+ print(f"Average F1 Score: {avg_f1:.2f}")
76
+ print(f"Average Execution Time: {avg_execution_time:.2f} seconds per file")
77
+ else:
78
+ print("No matching text files found for any images.")
79
 
80
+ if __name__ == "__main__":
81
+ main()