sandyyuan commited on
Commit
83d04a1
·
verified ·
1 Parent(s): c8ef0a5

Upload optimized_feature_engineering.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. optimized_feature_engineering.py +149 -0
optimized_feature_engineering.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Optimized feature extractor for document classification.
3
+ Contains 20 most effective features including contextual patterns from neighboring lines.
4
+ """
5
+ import numpy as np
6
+ import pandas as pd
7
+ import re
8
+
9
+ class OptimizedFeatureExtractor:
10
+ """Extract 20 optimized features for document line classification with contextual information."""
11
+
12
+ def __init__(self):
13
+ # Keywords that suggest different document types
14
+ self.form_keywords = [
15
+ 'name', 'date', 'address', 'phone', 'email', 'signature',
16
+ 'number', 'ssn', 'dob', 'zip', ':', '_____'
17
+ ]
18
+ self.table_keywords = [
19
+ 'total', 'qty', 'quantity', 'price', 'amount', 'item',
20
+ 'cost', 'subtotal', 'tax', '%', '$'
21
+ ]
22
+
23
+ # Selected features (in order of importance)
24
+ self.selected_features = ['word_count', 'line_position_ratio', 'line_length', 'avg_word_length', 'column_count', 'prev_line_length', 'digit_ratio', 'next_line_length', 'uppercase_ratio', 'next_line_digit_ratio', 'next_line_word_count', 'surrounded_by_form_pattern', 'prev_line_word_count', 'prev_line_digit_ratio', 'form_keyword_count', 'special_char_count', 'next_line_form_keyword_count', 'next_line_special_char_count', 'prev_line_form_keyword_count', 'prev_line_special_char_count']
25
+
26
+ def _extract_basic_features(self, line):
27
+ """Extract core text features for a single line."""
28
+ # Handle NaN or None values
29
+ if not line or pd.isna(line):
30
+ line = ""
31
+ else:
32
+ line = str(line) # Ensure it's a string
33
+
34
+ words = line.split()
35
+ line_lower = line.lower()
36
+
37
+ # Only compute features that are in our selected set
38
+ basic_features = {}
39
+
40
+ if 'line_length' in self.selected_features:
41
+ basic_features['line_length'] = len(line)
42
+ if 'word_count' in self.selected_features:
43
+ basic_features['word_count'] = len(words)
44
+ if 'avg_word_length' in self.selected_features:
45
+ basic_features['avg_word_length'] = len(line) / max(len(words), 1)
46
+ if 'starts_with_whitespace' in self.selected_features:
47
+ basic_features['starts_with_whitespace'] = 1 if line.startswith(' ') else 0
48
+ if 'digit_ratio' in self.selected_features:
49
+ basic_features['digit_ratio'] = sum(c.isdigit() for c in line) / max(len(line), 1)
50
+ if 'uppercase_ratio' in self.selected_features:
51
+ basic_features['uppercase_ratio'] = sum(c.isupper() for c in line) / max(sum(c.isalpha() for c in line), 1)
52
+ if 'special_char_count' in self.selected_features:
53
+ basic_features['special_char_count'] = sum(not c.isalnum() and not c.isspace() for c in line)
54
+ if 'ends_with_colon' in self.selected_features:
55
+ basic_features['ends_with_colon'] = 1 if line.strip().endswith(':') else 0
56
+ if 'has_underscore_field' in self.selected_features:
57
+ basic_features['has_underscore_field'] = 1 if '___' in line else 0
58
+ if 'is_all_caps' in self.selected_features:
59
+ basic_features['is_all_caps'] = 1 if line.isupper() and len(line.strip()) > 1 else 0
60
+ if 'has_currency' in self.selected_features:
61
+ basic_features['has_currency'] = 1 if '$' in line else 0
62
+ if 'has_percentage' in self.selected_features:
63
+ basic_features['has_percentage'] = 1 if '%' in line else 0
64
+ if 'has_email_pattern' in self.selected_features:
65
+ basic_features['has_email_pattern'] = 1 if '@' in line and '.' in line else 0
66
+ if 'has_phone_pattern' in self.selected_features:
67
+ basic_features['has_phone_pattern'] = 1 if re.search(r'\d{3}[-.\s]?\d{3}[-.\s]?\d{4}', line) else 0
68
+ if 'column_count' in self.selected_features:
69
+ basic_features['column_count'] = len(re.split(r'\s{2,}|\t', line.strip()))
70
+ if 'form_keyword_count' in self.selected_features:
71
+ basic_features['form_keyword_count'] = sum(1 for word in self.form_keywords if word in line_lower)
72
+ if 'table_keyword_count' in self.selected_features:
73
+ basic_features['table_keyword_count'] = sum(1 for word in self.table_keywords if word in line_lower)
74
+
75
+ return basic_features
76
+
77
+ def extract_features_for_line(self, line, all_lines=None, line_index=0):
78
+ """Extract features for a line including previous/next line context."""
79
+ # Get basic features for current line
80
+ features = self._extract_basic_features(line)
81
+
82
+ # Add positional features if selected
83
+ if 'line_position_ratio' in self.selected_features:
84
+ features['line_position_ratio'] = line_index / max(len(all_lines), 1) if all_lines else 0
85
+ if 'is_near_start' in self.selected_features:
86
+ features['is_near_start'] = 1 if all_lines and (line_index / max(len(all_lines), 1)) < 0.1 else 0
87
+ if 'is_near_end' in self.selected_features:
88
+ features['is_near_end'] = 1 if all_lines and (line_index / max(len(all_lines), 1)) > 0.9 else 0
89
+
90
+ # Add contextual features if selected and available
91
+ if all_lines and len(all_lines) > 1:
92
+ # Previous line features
93
+ if line_index > 0:
94
+ prev_line = all_lines[line_index - 1]
95
+ prev_features = self._extract_basic_features(prev_line)
96
+
97
+ for feat_name, feat_value in prev_features.items():
98
+ prev_feat_name = f'prev_{feat_name}'
99
+ if prev_feat_name in self.selected_features:
100
+ features[prev_feat_name] = feat_value
101
+
102
+ # Next line features
103
+ if line_index < len(all_lines) - 1:
104
+ next_line = all_lines[line_index + 1]
105
+ next_features = self._extract_basic_features(next_line)
106
+
107
+ for feat_name, feat_value in next_features.items():
108
+ next_feat_name = f'next_{feat_name}'
109
+ if next_feat_name in self.selected_features:
110
+ features[next_feat_name] = feat_value
111
+
112
+ # Contextual pattern features
113
+ if 'follows_label_pattern' in self.selected_features:
114
+ features['follows_label_pattern'] = 1 if line_index > 0 and \
115
+ self._extract_basic_features(all_lines[line_index - 1]).get('ends_with_colon', 0) and \
116
+ features.get('line_length', 0) < 50 else 0
117
+
118
+ if 'precedes_input_pattern' in self.selected_features:
119
+ features['precedes_input_pattern'] = 1 if line_index < len(all_lines) - 1 and \
120
+ features.get('ends_with_colon', 0) and \
121
+ self._extract_basic_features(all_lines[line_index + 1]).get('has_underscore_field', 0) else 0
122
+
123
+ if 'surrounded_by_form_pattern' in self.selected_features:
124
+ features['surrounded_by_form_pattern'] = 1 if line_index > 0 and line_index < len(all_lines) - 1 and \
125
+ (self._extract_basic_features(all_lines[line_index - 1]).get('form_keyword_count', 0) > 0 or \
126
+ self._extract_basic_features(all_lines[line_index + 1]).get('form_keyword_count', 0) > 0) else 0
127
+
128
+ # Fill missing features with 0
129
+ for feat_name in self.selected_features:
130
+ if feat_name not in features:
131
+ features[feat_name] = 0
132
+
133
+ return features
134
+
135
+ def extract_features_for_document(self, lines):
136
+ """Extract feature matrix for all lines in a document."""
137
+ if not lines:
138
+ return np.array([]), []
139
+
140
+ all_features = []
141
+
142
+ for i, line in enumerate(lines):
143
+ features = self.extract_features_for_line(line, lines, i)
144
+ # Convert to list in consistent order
145
+ feature_vector = [features[key] for key in sorted(self.selected_features)]
146
+ all_features.append(feature_vector)
147
+
148
+ feature_names = sorted(self.selected_features)
149
+ return np.array(all_features), feature_names