{{ message }}
Repository navigation
Expand file tree
/
Copy pathv4.py
More file actions
557 lines (533 loc) · 20.8 KB
/
Copy pathv4.py
File metadata and controls
557 lines (533 loc) · 20.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
import pandas as pd
import difflib
import re
import os
from colorama import Fore, init
from datetime import datetime
init(autoreset=True)
validation_rules = {
"Timestamp": {"type": "Date & Time", "mandatory": True},
"Date": {"type": "Date", "mandatory": True},
"Village": {"type": "Text", "mandatory": True},
"Panchayath": {"type": "Text", "mandatory": True},
"Individual Unique ID": {
"type": "Text",
"mandatory": True,
"special_rule": "dc_to_99"
},
"Name": {"type": "Text", "mandatory": True},
"ID Proof Type": {
"type": "SingleSelect",
"mandatory": True,
"valid_values": ["Ration Card", "Voters ID", "Not available"]
},
"ID Proof Number": {
"type": "Text",
"mandatory_if": {
"column": "ID Proof Type",
"not_value": "Not available"
}
},
"Number of Family members": {"type": "Number", "mandatory": True},
"Status": {
"type": "SingleSelect",
"mandatory": True,
"valid_values": ["In Person", "Absent"]
},
"Gender": {
"type": "SingleSelect",
"mandatory": True,
"valid_values": ["Male", "Female"]
},
"Contact Number": {
"type": "Number",
"mandatory_if": {
"column": "Status",
"value": "In Person"
},
"special_rule": "phone_number"
},
"Marital Status": {
"type": "SingleSelect",
"mandatory": False,
"valid_values": ["Single", "Married", "Widow", "Divorced", "Separated"]
},
"Father's Name": {
"type": "Text",
"mandatory": True,
"special_rule": "remove_slash"
},
"Age": {
"type": "Number",
"mandatory": True,
"range": {"min": 18, "max": 100}
},
"Weight (in kg)": {
"type": "Number",
"mandatory_if_not": {
"column": "Status",
"value": "Absent"
},
"range": {"min": 20, "max": 150}
},
"Height (in cm)": {
"type": "Number",
"mandatory_if_not": {
"column": "Status",
"value": "Absent"
},
"range": {"min": 100, "max": 200}
},
"Religion": {
"type": "SingleSelect",
"mandatory_if_not": {
"column": "Status",
"value": "Absent"
},
"valid_values": ["Hindu", "Muslim", "Christian", "Buddhist", "Others"]
},
"Education": {
"type": "SingleSelect",
"mandatory_if_not": {
"column": "Status",
"value": "Absent"
},
"valid_values": ["No schooling", "upto 5th Standard", "upto 7th Standard",
"SSLC", "PUC", "Diploma", "Graduation", "Post graduation"]
},
"Occupation Group - According to NCO 2015": {
"type": "SingleSelect",
"mandatory_if_not": {
"column": "Status",
"value": "Absent"
},
"valid_values": [
"Legislators, Senior Officials and Managers - Group 1",
"Professionals - Group 2",
"Technicians and associate professionals - Group 3",
"Clerks/Clerical support workers - Group 4",
"Service and sales workers - Group 5",
"Skilled agricultural, forestry and fishery workers - Group 6",
"Craft and related trader workers - Group 7",
"Plant and machine operators and assemblers - Group 8",
"Elementary occupations - Group 9",
"Workers not classified by Occupations - Group 10"
]
},
"Estimated Annual Family Income": {
"type": "SingleSelect",
"mandatory_if_not": {
"column": "Status",
"value": "Absent"
},
"valid_values": [
"less than INR 12,500",
"between INR 12,500 to INR 50,000",
"between INR 50,000 to INR 3,00,000",
"More than INR 3,00,000"
]
},
"Have you heard about cancer?": {
"type": "SingleSelect",
"mandatory_if_not": {
"column": "Status",
"value": "Absent"
},
"valid_values": ["Yes", "No", "Absent"]
},
"Are you aware of the symptoms/warning signs of cancer?": {
"type": "SingleSelect",
"mandatory_if_not": {
"column": "Status",
"value": "Absent"
},
"valid_values": ["Yes", "No", "Absent"]
},
"Do you think tobacco causes cancer?": {
"type": "SingleSelect",
"mandatory_if_not": {
"column": "Status",
"value": "Absent"
},
"valid_values": ["Yes", "No", "Absent"]
},
"Can cancer spread from one person to another?": {
"type": "SingleSelect",
"mandatory_if_not": {
"column": "Status",
"value": "Absent"
},
"valid_values": ["Yes", "No", "Absent"]
},
"Is there treatment and cure for cancer?": {
"type": "SingleSelect",
"mandatory_if_not": {
"column": "Status",
"value": "Absent"
},
"valid_values": ["Yes", "No", "Absent"]
},
"Do you currently use tobacco in any form?": {
"type": "SingleSelect",
"mandatory_if_not": {
"column": "Status",
"value": "Absent"
},
"valid_values": ["Yes", "Not Now", "Never"]
},
"Exposure to second hand smoke": {
"type": "SingleSelect",
"mandatory_if_not": {
"column": "Status",
"value": "Absent"
},
"valid_values": [
"At place of work",
"At home",
"In public",
"None"
]
}
}
def select_excel_file():
current_dir = os.getcwd()
excel_files = [f for f in os.listdir(current_dir) if f.endswith('.xlsx') or f.endswith('.xls')]
if not excel_files:
print(f"{Fore.RED}No Excel files found in the current directory.")
return None
print(f"{Fore.GREEN}Available Excel files:")
for i, file in enumerate(excel_files, 1):
print(f"{i}. {file}")
while True:
try:
selection = input(f"{Fore.YELLOW}Enter the number of the file you want to process (1-{len(excel_files)}): ")
file_index = int(selection) - 1
if 0 <= file_index < len(excel_files):
return os.path.join(current_dir, excel_files[file_index])
else:
print(f"{Fore.RED}Invalid selection. Please try again.")
except ValueError:
print(f"{Fore.RED}Please enter a valid number.")
def clean_column_name(name):
return re.sub(r'\s+', ' ', str(name).strip()).lower()
def map_columns(actual_columns, expected_columns):
column_mapping = {}
actual_clean_to_original = {clean_column_name(col): col for col in actual_columns}
expected_clean_to_original = {clean_column_name(col): col for col in expected_columns}
actual_clean = list(actual_clean_to_original.keys())
expected_clean = list(expected_clean_to_original.keys())
for expected_clean, expected_original in expected_clean_to_original.items():
matches = difflib.get_close_matches(expected_clean, actual_clean, n=1, cutoff=0.6)
if matches:
actual_clean_match = matches[0]
actual_original = actual_clean_to_original[actual_clean_match]
column_mapping[actual_original] = expected_original
print(f"{Fore.GREEN}Mapped column: '{actual_original}' -> '{expected_original}'")
else:
print(f"{Fore.YELLOW}Warning: No match found for column '{expected_original}'")
return column_mapping
def set_value_with_dtype_check(df, idx, col, new_val, expected_col=None):
try:
if expected_col and "contact number" in expected_col.lower():
if isinstance(new_val, str):
new_val = re.sub(r'\D', '', new_val)
if new_val:
df.at[idx, col] = pd.to_numeric(new_val)
else:
df.at[idx, col] = new_val
else:
col_dtype = df[col].dtype
if pd.api.types.is_numeric_dtype(col_dtype):
try:
df.at[idx, col] = pd.to_numeric(new_val)
except:
df.at[idx, col] = new_val
else:
df.at[idx, col] = new_val
except:
df.at[idx, col] = new_val
def is_number(val):
if pd.isna(val):
return False
try:
float(val)
return True
except:
return False
def is_date(val):
if pd.isna(val):
return False
try:
pd.to_datetime(val)
return True
except:
return False
def is_text(val):
if pd.isna(val):
return False
return isinstance(val, str)
def validate_value(val, rule, expected_col=None):
rule_type = rule.get("type", "").lower()
if pd.isna(val) or val == "":
return True
if expected_col and "individual unique id" in expected_col.lower():
return True
if rule_type == "number":
if not is_number(val):
return False
if "range" in rule:
try:
num_val = float(val)
min_val = rule["range"].get("min", float("-inf"))
max_val = rule["range"].get("max", float("inf"))
return min_val <= num_val <= max_val
except:
return False
return True
elif rule_type in ["date", "date & time"]:
return is_date(val)
elif rule_type == "text":
return is_text(val)
elif rule_type == "singleselect" and expected_col != "Exposure to second hand smoke":
valid_values = rule.get("valid_values", [])
val_str = str(val).strip().lower()
valid_lower = [v.lower() for v in valid_values]
return val_str in valid_lower
elif expected_col == "Exposure to second hand smoke":
if isinstance(val, str):
values = [v.strip().lower() for v in val.split(';')]
valid_lower = [v.lower() for v in rule.get("valid_values", [])]
return all(v in valid_lower for v in values)
return True
def apply_special_rule(val, rule_name, expected_col=None):
if rule_name == "dc_to_99":
if pd.isna(val) or val == "":
return val
val_str = str(val).strip()
if expected_col and "individual unique id" in expected_col.lower():
if val_str.isdigit() and len(val_str) == 4:
return val_str
if val_str.isdigit() and len(val_str) == 3:
return "0" + val_str
if val_str.isdigit() and len(val_str) not in [3, 4]:
return val_str
if re.match(r'^dc', val_str, re.IGNORECASE):
numeric_part = re.sub(r'^dc', '', val_str, re.IGNORECASE)
try:
num = int(numeric_part)
return f"99{num:02d}"
except:
return val_str
else:
try:
num = int(val_str)
return f"{num:04d}"
except:
return val_str
elif rule_name == "remove_slash":
if pd.isna(val) or val == "":
return val
return str(val).replace("/", "")
elif rule_name == "phone_number":
if pd.isna(val) or val == "":
return val
val_str = re.sub(r'\D', '', str(val))
if len(val_str) == 10:
return val_str
else:
return val
return val
def prompt_user(row_idx, col_name, val, rule):
print(f"{Fore.YELLOW}Row {row_idx+2}, Column '{col_name}':")
# Special handling for Exposure column with multiple values
if col_name == "Exposure to second hand smoke":
items = [v.strip() for v in val.split(";")]
valid_values = rule.get("valid_values", [])
valid_lower = [v.lower() for v in valid_values]
invalid_items = [i for i in items if i.lower() not in valid_lower]
if not invalid_items:
# Everything valid, no prompt needed
return val
print(f" Found value(s): {items}")
print(f" Valid options are: {valid_values}")
print(f" Invalid value(s): {invalid_items}")
print("Options:")
print(" 1. Manually correct")
print(" 2. Delete value")
print(" 3. Skip")
choice = input("Please enter option (1/2/3): ")
if choice == "1":
new_val = input("Enter corrected value(s) separated by semicolon: ")
return new_val
elif choice == "2":
return ""
else:
return val
else:
print(f" Found value: '{val}'")
rule_type = rule.get("type", "").lower()
suggestion = None
if rule_type == "singleselect":
valid_values = rule.get("valid_values", [])
val_lower = str(val).strip().lower()
valid_values_lower = [v.lower() for v in valid_values]
for i, lower_val in enumerate(valid_values_lower):
if val_lower == lower_val:
suggestion = valid_values[i]
break
else:
matches = difflib.get_close_matches(val_lower, valid_values_lower, n=1, cutoff=0.6)
if matches:
match_index = valid_values_lower.index(matches[0])
suggestion = valid_values[match_index]
print(f" Expected one of: {valid_values}")
elif rule_type == "number" and "range" in rule:
min_val = rule["range"].get("min", float("-inf"))
max_val = rule["range"].get("max", float("inf"))
print(f" Expected value between {min_val} and {max_val}")
if is_number(val):
num_val = float(val)
if num_val < min_val:
suggestion = str(min_val)
elif num_val > max_val:
suggestion = str(max_val)
else:
print(f" Expected type: {rule_type}")
if "special_rule" in rule:
special_rule = rule["special_rule"]
special_val = apply_special_rule(val, special_rule)
if special_val != val:
suggestion = special_val
print("Options:")
if suggestion:
print(f" 1. Auto-correct to: '{suggestion}'")
else:
print(" 1. [No auto-suggestion available]")
print(" 2. Manually correct")
print(" 3. Delete value")
print(" 4. Skip")
choice = input("Please enter option (1/2/3/4): ")
if choice == "1" and suggestion:
return suggestion
elif choice == "2":
new_val = input("Enter corrected value: ")
return new_val
elif choice == "3":
return ""
else:
return val
def find_mapped_column(column_name, column_mapping):
for actual_col, expected_col in column_mapping.items():
if expected_col == column_name:
return actual_col
return None
def is_mandatory(row, expected_col, rule, column_mapping):
if rule.get("mandatory", False):
return True
if "mandatory_if" in rule:
cond = rule["mandatory_if"]
other_expected_col = cond.get("column", "")
expected_val = cond.get("value", "")
not_expected_val = cond.get("not_value", "")
other_actual_col = find_mapped_column(other_expected_col, column_mapping)
if other_actual_col and other_actual_col in row.index:
other_val = row[other_actual_col]
if expected_val and str(other_val).strip().lower() == expected_val.lower():
return True
if not_expected_val and str(other_val).strip().lower() != not_expected_val.lower():
return True
if "mandatory_if_not" in rule:
cond = rule["mandatory_if_not"]
other_expected_col = cond.get("column", "")
exclusion_val = cond.get("value", "")
other_actual_col = find_mapped_column(other_expected_col, column_mapping)
if other_actual_col and other_actual_col in row.index and str(row[other_actual_col]).strip().lower() != exclusion_val.lower():
return True
return False
def normalize_value(val, rule):
if pd.isna(val) or val == "":
return val
rule_type = rule.get("type", "").lower()
if rule_type == "singleselect":
valid_values = rule.get("valid_values", [])
val_str = str(val).strip()
val_lower = val_str.lower()
for template_val in valid_values:
if template_val.lower() == val_lower:
return template_val
return val
def main():
survey_path = select_excel_file()
if not survey_path:
print(f"{Fore.RED}No file selected. Exiting.")
return
try:
survey = pd.read_excel(survey_path)
print(f"{Fore.GREEN}Successfully loaded survey file with {len(survey)} rows.")
except Exception as e:
print(f"{Fore.RED}Error loading survey file: {e}")
return
column_mapping = map_columns(survey.columns, list(validation_rules.keys()))
reverse_mapping = {v: k for k, v in column_mapping.items()}
report = []
for idx, row in survey.iterrows():
for expected_col, rule in validation_rules.items():
actual_col = reverse_mapping.get(expected_col)
if not actual_col:
print(f"{Fore.RED}Warning: No match found for expected column '{expected_col}'")
continue
val = row[actual_col]
if (pd.isna(val) or str(val).strip() == "") and is_mandatory(row, expected_col, rule, column_mapping):
print(f"{Fore.RED}Row {idx+2} Missing mandatory value in '{actual_col}' (maps to '{expected_col}')")
report.append(f"Row {idx+2} Missing mandatory value in {actual_col}")
continue
if pd.isna(val) or str(val).strip() == "":
continue
normalized_val = normalize_value(val, rule)
if normalized_val != val:
set_value_with_dtype_check(survey, idx, actual_col, normalized_val, expected_col)
report.append(f"Row {idx+2} Column '{actual_col}': Normalized case from '{val}' to '{normalized_val}'")
val = normalized_val
if expected_col == "Exposure to second hand smoke":
if pd.notna(val) and str(val).strip() != "":
val = str(val).replace(",", ";").strip()
val = ";".join(v.strip() for v in val.split(";"))
set_value_with_dtype_check(survey, idx, actual_col, val, expected_col)
report.append(f"Row {idx+2} Column '{actual_col}': Converted value to semicolon-separated '{val}'")
if "special_rule" in rule and "individual unique id" in expected_col.lower():
special_rule = rule["special_rule"]
special_val = apply_special_rule(val, special_rule, expected_col)
val_str = str(val).strip()
if val_str.isdigit() and len(val_str) == 3:
set_value_with_dtype_check(survey, idx, actual_col, special_val, expected_col)
report.append(f"Row {idx+2} Column '{actual_col}': Auto-formatted '{val}' to '{special_val}'")
continue
elif val_str.isdigit() and len(val_str) == 4:
continue
if not validate_value(val, rule, expected_col):
new_val = prompt_user(idx, actual_col, val, rule)
if new_val != val:
set_value_with_dtype_check(survey, idx, actual_col, new_val, expected_col)
report.append(f"Row {idx+2} Column '{actual_col}': Changed '{val}' to '{new_val}'")
elif "special_rule" in rule:
special_rule = rule["special_rule"]
special_val = apply_special_rule(val, special_rule, expected_col)
if str(special_val).strip() != str(val).strip():
print(f"{Fore.YELLOW}Row {idx+2}, Column '{actual_col}':")
print(f" Found value: '{val}'")
print(f" Auto-corrected to: '{special_val}' (based on special rule)")
print(" Press Enter to accept or type 'n' to keep original value:")
response = input()
if response.lower() != "n":
set_value_with_dtype_check(survey, idx, actual_col, special_val, expected_col)
report.append(f"Row {idx+2} Column '{actual_col}': Applied special rule, changed '{val}' to '{special_val}'")
output_excel = survey_path.replace('.xlsx', '_CLEANED.xlsx')
report_file = survey_path.replace('.xlsx', '_REPORT.txt')
survey.to_excel(output_excel, index=False)
with open(report_file, 'w') as f:
for line in report:
f.write(line + '\n')
print(f"{Fore.GREEN}Cleaning complete! Cleaned file saved to: {output_excel}")
print(f"{Fore.GREEN}Report saved to: {report_file}")
if __name__ == "__main__":
main()
You can’t perform that action at this time.
