Spaces:
Sleeping

mhpl commited on
Commit
7e7d642
·
verified ·
1 Parent(s): 34a733e

Delete rr_cleaning/health_studio.py

Browse files
Files changed (1) hide show
  1. rr_cleaning/health_studio.py +0 -807
rr_cleaning/health_studio.py DELETED
@@ -1,807 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- """health_studio.ipynb
3
-
4
- Automatically generated by Colab.
5
-
6
- Original file is located at
7
- https://colab.research.google.com/drive/1EY7MkkWNMs4qo229tg1fn9feI3PrMo3o
8
- """
9
-
10
- """
11
- HTML to Excel Converter for Hospital Revenue Report (Stable Version)
12
- """
13
-
14
- import pandas as pd
15
- from bs4 import BeautifulSoup
16
- import os
17
-
18
- def convert_html_to_excel(input_file, output_file):
19
- # 1. Read the HTML file with verification
20
- print(f"\n[1/6] Reading HTML file: {os.path.basename(input_file)}")
21
- with open(input_file, 'r', encoding='utf-8', errors='ignore') as f:
22
- html_content = f.read()
23
- print("✓ File read successfully")
24
-
25
- # 2. Parse HTML with lxml for consistency
26
- print("[2/6] Parsing HTML content...")
27
- soup = BeautifulSoup(html_content, 'lxml')
28
- tables = soup.find_all('table')
29
- print(f"✓ Found {len(tables)} tables in document")
30
-
31
- # 3. Identify main table by headers
32
- print("[3/6] Locating main data table...")
33
- expected_headers = ['Patient Type', 'Admission No.'] # UPDATE THESE
34
- main_table = None
35
-
36
- for i, table in enumerate(tables):
37
- first_row = table.find('tr')
38
- if first_row:
39
- headers = [th.get_text(strip=True) for th in first_row.find_all(['th', 'td'])]
40
- if all(h in headers for h in expected_headers):
41
- main_table = table
42
- print(f"✓ Identified table {i+1} as main data table")
43
- print(f" Table dimensions: {len(table.find_all('tr'))} rows")
44
- break
45
-
46
- if not main_table:
47
- raise ValueError("× ERROR: Could not find main data table with expected headers")
48
-
49
- # 4. Extract and validate data rows
50
- print("[4/6] Processing table rows...")
51
- rows = main_table.find_all('tr')
52
- header_row = rows[0]
53
- headers = [col.get_text(strip=True) for col in header_row.find_all(['th', 'td'])]
54
- valid_col_count = len(headers)
55
-
56
- print(f"✓ Header row identified with {valid_col_count} columns:")
57
- print(f" {headers}")
58
- print(f"✓ Processing {len(rows)-1} data rows...")
59
-
60
- # Process data rows with validation
61
- data = []
62
- skipped_rows = 0
63
- for i, row in enumerate(rows[1:]): # Skip header
64
- cols = row.find_all(['td', 'th'])
65
- if len(cols) != valid_col_count:
66
- skipped_rows += 1
67
- continue
68
- data.append([col.get_text(strip=True) for col in cols])
69
-
70
- print(f"✓ Clean rows extracted: {len(data)}")
71
- print(f" Skipped {skipped_rows} malformed rows")
72
-
73
- # [5/6] Total Row Removal (Guaranteed Last Row + "Total Net Amount" Check)
74
- print("[5/6] Checking for total row...")
75
-
76
- if data:
77
- last_row = data[-1]
78
-
79
- # Check if "total net amount" exists in ANY cell of the last row
80
- if any("total net amount" in cell.lower() for cell in last_row):
81
- print("✓ Removed TOTAL NET AMOUNT row")
82
- data = data[:-1]
83
-
84
- print(f"✓ Final data rows: {len(data)}")
85
-
86
- # 6. Create and save DataFrame
87
- print("[6/6] Creating Excel file...")
88
- df = pd.DataFrame(data, columns=headers)
89
-
90
- # Final verification
91
- print(f"✓ DataFrame created with dimensions: {df.shape}")
92
- print(f"✓ First 3 columns: {df.columns.tolist()[:3]}...")
93
- print(f"✓ Last 3 columns: {df.columns.tolist()[-3:]}...")
94
-
95
- df.to_excel(output_file, index=False)
96
- print(f"\nProcessing complete! Saved to: {output_file}")
97
- print(f"Final verification:")
98
- print(f"- Total rows: {len(df):,}")
99
- print(f"- Total columns: {len(df.columns):,}")
100
-
101
- return output_file
102
-
103
- import pandas as pd
104
- import numpy as np
105
- import re
106
- from collections import Counter
107
-
108
- def preprocess_hospital_revenue(input_file, output_file):
109
- """
110
- Processes hospital revenue data with specific transformations:
111
- - Service Type modifications
112
- - Department category standardization
113
- - Billing Category conversions
114
- """
115
- # Step 1: Load the Excel file
116
- try:
117
- df = pd.read_excel(input_file)
118
- print(f"Successfully loaded file with {df.shape[0]} rows and {df.shape[1]} columns")
119
- except Exception as e:
120
- print(f"Error loading file: {e}")
121
- return False
122
-
123
- # Step 2: Convert numerical columns to numbers
124
- numerical_columns = ['Qty', 'Amount', 'Discount', 'Net Amount']
125
-
126
- # Function to convert currency values to numbers
127
- def convert_to_number(value):
128
- if pd.isna(value):
129
- return 0.0 # Handle NaN values
130
- if isinstance(value, (int, float)):
131
- return float(value)
132
- if isinstance(value, str):
133
- # Remove currency symbols, commas, spaces, and other non-numeric characters
134
- cleaned_value = value.replace('₹', '').replace(',', '').replace(' ', '')
135
- # Handle other currency symbols
136
- for symbol in ['$', '€', '£', '¥']:
137
- cleaned_value = cleaned_value.replace(symbol, '')
138
- try:
139
- return float(cleaned_value)
140
- except ValueError:
141
- print(f"Warning: Could not convert '{value}' to number, using 0")
142
- return 0.0
143
- return 0.0
144
-
145
- # Apply conversion to numerical columns
146
- for col in numerical_columns:
147
- if col in df.columns:
148
- df[col] = df[col].apply(convert_to_number)
149
- print(f"Converted {col} to numeric format")
150
- else:
151
- print(f"Warning: Column '{col}' not found in the data")
152
-
153
- # Step 3: Create data and final dataframes
154
- data = df.copy() # First dataframe is a copy of the original data
155
- final = df.copy() # Second dataframe is where we'll apply transformations
156
-
157
- # Step 4: Service Type OP Pharmacy Return to OP Pharmacy
158
- print("\nProcessing Service Types...")
159
- service_mapping = {
160
- 'OPD Pharmacy Return': 'OPD Pharmacy',
161
- }
162
- final['Service Type'] = final['Service Type'].replace(service_mapping)
163
- print(f"Updated {len(service_mapping)} service types")
164
-
165
- #Step 5: Put Service Types 'Other Charges' and 'OPD Package' all records to 'Homecare' and 'Package'
166
- # Deptt. Values respectively
167
-
168
- # Process OPD Package departments
169
- print("\nProcessing OPD Package departments...")
170
- opd_package_indices = final.index[
171
- final['Service Type'].apply(
172
- lambda x: re.sub(r'[^A-Za-z]', '', str(x)).lower() == 'opdpackage'
173
- )
174
- ]
175
-
176
- for idx in opd_package_indices:
177
- final.loc[idx, 'Dr. Department'] = 'Package'
178
- print(f"Updated {len(opd_package_indices)} OPD Package records")
179
-
180
- # Process Other Charges departments
181
- print("\nProcessing Other Charges departments...")
182
- other_charges_indices = final.index[
183
- final['Service Type'].apply(
184
- lambda x: re.sub(r'[^A-Za-z]', '', str(x)).lower() == 'othercharges'
185
- )
186
- ]
187
-
188
- for idx in other_charges_indices:
189
- final.loc[idx, 'Dr. Department'] = 'Homecare'
190
- print(f"Updated {len(other_charges_indices)} Other Charges records")
191
-
192
-
193
- # Step 6: Process all the blank Department Values
194
- # Modified blank department handling for OPD-only data
195
- def is_blank(value):
196
- if pd.isna(value):
197
- return True
198
- if isinstance(value, str):
199
- if value.strip() == '' or value.lower() in ['null', 'na', 'n/a', 'none']:
200
- return True
201
- return False
202
-
203
- # Identify blank departments
204
- final['is_blank_dept'] = final['Dr. Department'].apply(is_blank)
205
-
206
- # Get indices of blank departments (no patient type filter needed)
207
- blank_dept_indices = final[final['is_blank_dept']].index
208
- print(f"Found {len(blank_dept_indices)} blank departments")
209
-
210
- # Process blank departments based on Service Type
211
- for idx in blank_dept_indices:
212
- service_type = final.loc[idx, 'Service Type']
213
-
214
- # Handle blank service types first
215
- if is_blank(service_type):
216
- final.loc[idx, 'Dr. Department'] = "Other OPD Revenue"
217
- continue
218
-
219
- # Clean and normalize service type
220
- service_type_clean = re.sub(r'[^A-Za-z]', '', str(service_type)).lower()
221
-
222
- # Diagnostic/Pathology handling
223
- if service_type_clean == 'diagnostic':
224
- final.loc[idx, 'Dr. Department'] = 'Diagnostic'
225
- elif service_type_clean == 'pathology':
226
- final.loc[idx, 'Dr. Department'] = 'Pathology'
227
- else:
228
- final.loc[idx, 'Dr. Department'] = "Other OPD Revenue"
229
-
230
- # Cleanup temporary column
231
- final = final.drop('is_blank_dept', axis=1)
232
-
233
- # Validation Check
234
- # Final validation check
235
- blank_check = final['Dr. Department'].apply(is_blank)
236
- remaining_blanks = blank_check.sum()
237
-
238
- if remaining_blanks == 0:
239
- print("\nSuccess: All departments have been populated")
240
- else:
241
- print(f"\nWarning: {remaining_blanks} blank departments remain")
242
- print("Affected Service Types:")
243
- print(final[blank_check]['Service Type'].value_counts())
244
-
245
- #All department values are now filled.
246
-
247
- # Step 7:
248
- # Replace RADIOLOGY with Diagnostic for all OPD patients (simplified)
249
- radiology_mask = final['Dr. Department'].apply(
250
- lambda x: 'radiology' in re.sub(r'[^A-Za-z]', '', str(x)).lower())
251
-
252
- radiology_indices = final[radiology_mask].index
253
- print(f"Found {len(radiology_indices)} patients in RADIOLOGY department")
254
-
255
- # Vectorized replacement (no loop needed)
256
- final.loc[radiology_indices, 'Dr. Department'] = "Diagnostic"
257
-
258
- # Step 8:
259
- # Replace Dr. General Physician Records of Internal Medicine Department to Other OPD Revenue
260
- # Normalize doctor name function (as specified)
261
- def normalize_doctor_name(name: str) -> str:
262
- """Normalize doctor names to plain lowercase alphabetic."""
263
- if pd.isna(name) or not isinstance(name, str):
264
- return ""
265
- name = re.sub(r'^dr[.\s]*', '', name, flags=re.IGNORECASE) # Remove 'Dr' prefix
266
- name = re.sub(r'[^A-Za-z]', '', name) # Remove non-alphabetic characters
267
- return name.lower().strip()
268
-
269
- # Create mask for target records
270
- mask = (
271
- (final['Dr. Name'].apply(normalize_doctor_name) == 'generalphysician') &
272
- (final['Dr. Department'].apply(lambda x: re.sub(r'[^A-Za-z]', '', str(x)).lower() == 'internalmedicine')))
273
-
274
- # Update department for matching records
275
- final.loc[mask, 'Dr. Department'] = 'Other OPD Revenue'
276
-
277
- # Step 9: Merge Extra Departments to Other OPD Revenue
278
- # Define departments to merge (case-insensitive exact match)
279
- departments_to_merge = [
280
- 'Gastro Entrology',
281
- 'ENDOCRINOLOGY',
282
- 'ONCO SURGERY',
283
- 'RESPIRATORY MEDICINE',
284
- 'MEDICAL ONCOLOGY',
285
- 'Nephrology',
286
- 'Neuro Surgery',
287
- 'NUTRITIONIST and DIE',
288
- 'Orthopaedics',
289
- 'Respiratory Medicine'
290
- ]
291
-
292
- # Create lowercase and without spaces version of target departments for matching
293
- target_cleaned = [
294
- re.sub(r'[^A-Za-z]', '', dept).lower()
295
- for dept in departments_to_merge]
296
-
297
- # Create boolean mask using robust cleaning logic
298
- merge_mask = final['Dr. Department'].apply(
299
- lambda x: re.sub(r'[^A-Za-z]', '', str(x)).lower() in target_cleaned)
300
-
301
- # Get pre-merge counts for verification
302
- original_counts = final[merge_mask]['Dr. Department'].value_counts()
303
- to_merge_count = merge_mask.sum()
304
-
305
- print(f"Found {to_merge_count} entries to merge into Other OPD Revenue")
306
- print("Departments being merged:")
307
- print(original_counts)
308
-
309
- # Perform the merge
310
- final.loc[merge_mask, 'Dr. Department'] = "Other OPD Revenue"
311
-
312
- # Post-merge verification
313
- print("\nMerge completed!")
314
- print(f"New 'Other OPD Revenue' count: {(final['Dr. Department'] == 'Other OPD Revenue').sum()}")
315
- print(f"Remaining unique departments: {final['Dr. Department'].nunique()}")
316
-
317
- #--------------------------------------------------------------------------------------------------
318
- # Step 10: Format Dr. Department names to title case
319
- # -----------------------------------------------------------------------
320
-
321
- print("\nFormatting Dr. Department names to title case...")
322
- def format_department_name(dept):
323
- """Format department names to title case with special rules for conjunctions/prepositions"""
324
- if pd.isna(dept) or not isinstance(dept, str):
325
- return dept
326
-
327
- # Convert to lowercase
328
- dept = dept.lower()
329
-
330
- # Split into words
331
- words = dept.split()
332
-
333
- # Capitalize first letter of each word
334
- words = [word.capitalize() for word in words]
335
-
336
- # List of words to keep lowercase (except if they're the first word)
337
- lowercase_words = ["and", "the", "of", "in", "on", "at", "to", "from", "with", "by"]
338
-
339
- # Make specified words lowercase (except if they're the first word)
340
- for i in range(len(words)):
341
- if i > 0 and words[i].lower() in lowercase_words:
342
- words[i] = words[i].lower()
343
-
344
- # Join back with spaces
345
- return " ".join(words)
346
-
347
- # Apply the formatting to Dr. Department names
348
- dr_dept_before_formatting = final['Dr. Department'].copy()
349
- final['Dr. Department'] = final['Dr. Department'].apply(format_department_name)
350
-
351
- # Count how many Dr. Department names were changed by formatting
352
- formatted_count = (dr_dept_before_formatting != final['Dr. Department']).sum()
353
- print(f"Formatted {formatted_count} Dr. Department names to title case")
354
-
355
- # Print the unique Dr. Departments before and after formatting
356
- unique_before = dr_dept_before_formatting.fillna('Unknown').unique()
357
- unique_after = final['Dr. Department'].unique()
358
- print(f"Unique Dr. Departments before formatting: {len(unique_before)}")
359
- print(f"Unique Dr. Departments after formatting: {len(unique_after)}")
360
-
361
- # Show examples of changes for verification
362
- if formatted_count > 0:
363
- print("\nExamples of formatting changes:")
364
- changes = []
365
- for orig, new in zip(dr_dept_before_formatting, final['Dr. Department']):
366
- if orig != new and pd.notna(orig) and pd.notna(new):
367
- changes.append(f"'{orig}' → '{new}'")
368
- if len(changes) >= 5: # Show up to 5 examples
369
- break
370
- print("\n".join(changes[:5]))
371
-
372
- #-------------------------------------------------------------------
373
-
374
- # Step 10.5: Standardize department names and correct typos
375
- # Dictionary of department name corrections
376
- department_corrections = {
377
- # Original corrections
378
- 'Pediatric': 'Paediatrics',
379
- 'Pediatrics': 'Paediatrics',
380
- 'Paediatric': 'Paediatrics',
381
- 'Paediatric': 'Paediatrics',
382
- 'Peads': 'Paediatrics',
383
- 'Pead': 'Paediatrics',
384
- 'Child': 'Paediatrics',
385
- 'Children': 'Paediatrics',
386
-
387
- 'Obs & Gynae': 'Obs and Gynae',
388
- 'obsandgynae': 'Obs and Gynae',
389
- 'ObsAndGynae': 'Obs and Gynae',
390
- 'Obsgynae': 'Obs and Gynae',
391
- 'Obs&gynae': 'Obs and Gynae',
392
- 'Obstetrics': 'Obs and Gynae',
393
- 'Gynaecology': 'Obs and Gynae',
394
- 'Gynecology': 'Obs and Gynae',
395
- 'ObsGynae': 'Obs and Gynae',
396
-
397
- 'Ortho': 'Orthopaedics',
398
- 'Orthopedics': 'Orthopaedics',
399
- 'Orthopedic': 'Orthopaedics',
400
- 'Orthopaedic': 'Orthopaedics',
401
-
402
-
403
- 'Ent': 'ENT',
404
- 'E.n.t': 'ENT',
405
- 'E.n.t.': 'ENT',
406
- 'Ear Nose Throat': 'ENT',
407
-
408
- 'Neuro': 'Neurology',
409
-
410
-
411
- 'Cardio': 'Cardiology',
412
-
413
-
414
- 'Derma': 'Dermatology',
415
-
416
-
417
- 'Nephro': 'Nephrology',
418
-
419
- 'Gastro': 'Gastro Entrology',
420
- 'Gastroenterology': 'Gastro Entrology',
421
- 'Ge': 'Gastro Entrology',
422
- 'G.e.': 'Gastro Entrology',
423
-
424
- 'Pulmo': 'Pulmonology',
425
- 'Chest': 'Pulmonology',
426
-
427
- 'Dentistry': 'Dental',
428
-
429
- 'Ophthal': 'Ophthalmology',
430
- 'Opthalmology': 'Ophthalmology',
431
-
432
- 'Eye': 'Ophthalmology',
433
-
434
-
435
- 'Physio': 'Physiotherapy',
436
-
437
-
438
- 'Psych': 'Psychiatry',
439
- 'Mental': 'Psychiatry',
440
-
441
-
442
- 'Onco': 'Oncology',
443
- 'Cancer': 'Oncology',
444
-
445
-
446
- 'Endo': 'Endocrinology',
447
- 'Diabetes': 'Endocrinology',
448
-
449
- 'Uro': 'Urology',
450
-
451
- 'General': 'General Medicine',
452
- 'Gen Med': 'General Medicine',
453
- 'Surgery': 'General Surgery',
454
- 'Gen Surg': 'General Surgery',
455
-
456
- 'P Surgery': 'Plastic Surgery',
457
- 'Plastic': 'Plastic Surgery',
458
- 'PSurgery': 'Plastic Surgery',
459
-
460
- 'Other Opd Revenue': 'Other OPD Revenue',
461
-
462
- # New corrections preserving your EXACT report names
463
- 'Internal Med': 'Internal Medicine',
464
- 'Gen Med': 'Internal Medicine',
465
- 'Int Med': 'Internal Medicine',
466
- 'Neurosurgery': 'Neuro Surgery',
467
- 'Neuro Surg': 'Neuro Surgery',
468
- 'Brain Surgery': 'Neuro Surgery',
469
- 'Nutrition & Die': 'Nutritionist and Dietrics',
470
- 'Dietrics': 'Nutritionist and Dietrics',
471
- 'Clinical Nutrition': 'Nutritionist and Dietrics',
472
- 'Radio Diagnosis': 'Radiology',
473
- 'X-Ray': 'Radiology',
474
- 'Pulmonary': 'Respiratory Medicine',
475
- 'Chest Med': 'Respiratory Medicine',
476
- 'Gastroenterology': 'Gastro Entrology',
477
- 'G.i.': 'Gastro Entrology',
478
- 'Oncosurgery': 'Onco Surgery',
479
- 'Cancer Surgery': 'Onco Surgery',
480
- 'Med Onco': 'Medical Oncology',
481
- 'Medicalonco': 'Medical Oncology'
482
- }
483
-
484
- def standardize_department(dept):
485
- if pd.isna(dept) or not isinstance(dept, str):
486
- return dept
487
-
488
- dept_clean = dept.strip()
489
-
490
- # Direct match first
491
- if dept_clean in department_corrections:
492
- return department_corrections[dept_clean]
493
-
494
- # Regex patterns for partial matches
495
- patterns = {
496
- r'P[AE][DIA]+TR': 'Pediatric',
497
- r'OBS.*GYN': 'Obs and Gynae',
498
- r'ORTH[OA]': 'Orthopaedics',
499
- r'NEURO.*SURG': 'Neuro Surgery',
500
- r'(NUTR|DIET)': 'Nutritionist and Dietrics',
501
- r'RAD(IO)?\b': 'Radiology',
502
- r'RESP(IRATORY)?|CHEST|PULMO': 'Respiratory Medicine',
503
- r'MED.*ONCO': 'Medical Oncology',
504
- r'GASTRO\W?ENT': 'Gastro Entrology'
505
- }
506
-
507
- for pattern, standardized in patterns.items():
508
- if re.search(pattern, dept_clean, re.IGNORECASE):
509
- return standardized
510
-
511
- return dept.strip() # Preserve original casing/spelling
512
-
513
- # Apply standardization
514
- dept_before = final['Dr. Department'].copy()
515
- final['Dr. Department'] = final['Dr. Department'].apply(standardize_department)
516
-
517
- # Count standardized departments
518
- standardized_count = (dept_before != final['Dr. Department']).sum()
519
- print(f"Standardized {standardized_count} department names")
520
-
521
- # Print unique counts
522
- unique_before = dept_before.unique()
523
- unique_after = final['Dr. Department'].unique()
524
- print(f"Unique departments before standardization: {len(unique_before)}")
525
- print(f"Unique departments after standardization: {len(unique_after)}")
526
-
527
- #---------------------------------------------------------------------------------------------------------------
528
-
529
- # Step 10: Process blank Billing Category values
530
- # Check for blank Billing Category values
531
- final['is_blank_billing'] = final['Billing Category'].apply(is_blank)
532
- blank_billing_count = final['is_blank_billing'].sum()
533
- print(f"Found {blank_billing_count} records with blank Billing Category")
534
-
535
- # For OPD Pharmacy and OPD Pharmacy Return service types, set to "Pharmacy Revenue"
536
- pharmacy_mask = final['is_blank_billing'] & final['Service Type'].isin(['OPD Pharmacy', 'OPD Pharmacy Return'])
537
- pharmacy_indices = final[pharmacy_mask].index
538
- print(f"Setting {len(pharmacy_indices)} blank Billing Category values to 'Pharmacy Revenue' based on Service Type")
539
-
540
- for idx in pharmacy_indices:
541
- final.loc[idx, 'Billing Category'] = "OP Pharmacy Revenue"
542
-
543
- # For any remaining blank values, set to "General"
544
- remaining_blank_mask = final['is_blank_billing'] & ~pharmacy_mask
545
- remaining_blank_indices = final[remaining_blank_mask].index
546
- print(f"Setting {len(remaining_blank_indices)} remaining blank Billing Category values to 'General'")
547
-
548
- for idx in remaining_blank_indices:
549
- final.loc[idx, 'Billing Category'] = "General"
550
-
551
- # Remove the temporary column
552
- final = final.drop('is_blank_billing', axis=1)
553
-
554
- # Step 11: Verify no invalid values remain
555
- print("\nDepartment distribution after processing:")
556
- dept_counts = final['Dr. Department'].value_counts()
557
- print(dept_counts)
558
-
559
- print("\nBilling Category distribution after processing:")
560
- billing_counts = final['Billing Category'].value_counts()
561
- print(billing_counts)
562
-
563
- # Step 12: Save the Excel File
564
- try:
565
- with pd.ExcelWriter(output_file, engine='openpyxl') as writer:
566
- # 1. Save Final sheet
567
- final.to_excel(writer, sheet_name='Final', index=False)
568
- data.to_excel(writer, sheet_name='Data', index=False)
569
-
570
- # 2. Create standardization mapping ONLY for changed departments
571
- # Get unique original-standardized pairs
572
- unique_pairs = pd.DataFrame({
573
- 'Original': dept_before.unique(),
574
- 'Standardized': [standardize_department(d) for d in dept_before.unique()]
575
- })
576
-
577
- # Filter only changed departments
578
- changed_depts = unique_pairs[unique_pairs['Original'] != unique_pairs['Standardized']]
579
-
580
- if not changed_depts.empty:
581
- changed_depts.to_excel(
582
- writer,
583
- sheet_name='_Dept_Standardization',
584
- index=False
585
- )
586
- print(f"Added {len(changed_depts)} department mappings")
587
-
588
- print(f"File saved successfully: {output_file}")
589
- return True
590
-
591
- except Exception as e:
592
- print(f"Save failed: {str(e)}")
593
- return False
594
-
595
- import pandas as pd
596
- import numpy as np
597
- import os
598
- from openpyxl.styles import PatternFill, Font
599
- from openpyxl.utils import get_column_letter
600
-
601
- def map_billing_categories_and_create_pivots(input_file, mapping_file, output_file):
602
- """
603
- Maps billing categories using a mapping file and creates pivot tables with grand totals.
604
-
605
- Parameters:
606
- input_file (str): Path to the processed hospital revenue Excel file
607
- mapping_file (str): Path to the billing category mapping Excel file
608
- output_file (str): Path to save the output Excel file with mapping and pivot tables
609
-
610
- Returns:
611
- bool: True if processing completed successfully, False otherwise
612
- """
613
- try:
614
- # Step 1: Load the processed Excel file
615
- print(f"Loading processed Excel file: {input_file}")
616
- # Read only the Final sheet
617
- with pd.ExcelFile(input_file) as xls:
618
- final_df = pd.read_excel(xls, sheet_name='Final')
619
- data_df = pd.read_excel(xls, sheet_name='Data')
620
-
621
- print(f"Loaded Final sheet with {final_df.shape[0]} rows and {final_df.shape[1]} columns")
622
-
623
- # Step 2: Load the mapping file
624
- print(f"Loading mapping file: {mapping_file}")
625
- mapping_df = pd.read_excel(mapping_file)
626
- print(f"Loaded mapping with {mapping_df.shape[0]} rows")
627
-
628
- # Create case-insensitive mapping dictionary
629
- mapping_dict = {}
630
- for _, row in mapping_df.iterrows():
631
- key = row.iloc[0]
632
- value = row.iloc[1]
633
- if not pd.isna(key):
634
- mapping_dict[str(key).lower()] = value
635
-
636
- print(f"Created case-insensitive mapping dictionary with {len(mapping_dict)} entries")
637
-
638
- # Step 3: Create new Mapping column
639
- billing_category_idx = final_df.columns.get_loc('Billing Category')
640
- mapping_values = []
641
- unmapped_count = 0
642
-
643
- for bc in final_df['Billing Category']:
644
- bc_key = str(bc).lower() if not pd.isna(bc) else ""
645
- if bc_key in mapping_dict:
646
- mapping_values.append(mapping_dict[bc_key])
647
- else:
648
- mapping_values.append('Unmapped')
649
- unmapped_count += 1
650
-
651
- final_df.insert(billing_category_idx + 1, 'Mapping', mapping_values)
652
- print(f"Added Mapping column: {len(mapping_values) - unmapped_count} mapped values, {unmapped_count} unmapped")
653
-
654
- # Step 4: Create pivot tables with grand totals
655
- # Function to create and format pivot tables
656
- def create_pivot(df, index_col):
657
- pivot = pd.pivot_table(
658
- df,
659
- values='Net Amount',
660
- index=index_col,
661
- aggfunc='sum',
662
- margins=True,
663
- margins_name='Grand Total'
664
- ).reset_index()
665
-
666
- # Sort and maintain Grand Total at bottom
667
- grand_total = pivot[pivot[index_col] == 'Grand Total']
668
- pivot = pivot[pivot[index_col] != 'Grand Total']
669
- pivot = pivot.sort_values('Net Amount', ascending=False)
670
- return pd.concat([pivot, grand_total]).round(0)
671
-
672
- print("Creating pivot tables")
673
- dept_pivot = create_pivot(final_df, 'Dr. Department')
674
- mapping_pivot = create_pivot(final_df, 'Mapping')
675
- service_pivot = create_pivot(final_df, 'Service Type')
676
-
677
- # Step 5: Save results to new Excel file
678
- print(f"Saving results to {output_file}")
679
- with pd.ExcelWriter(output_file, engine='openpyxl') as writer:
680
- # Write all pivots to first sheet with spacing
681
- dept_pivot.to_excel(writer, sheet_name='Pivot Tables', index=False, startrow=0)
682
- mapping_pivot.to_excel(writer, sheet_name='Pivot Tables', index=False,
683
- startrow=len(dept_pivot) + 3)
684
- service_pivot.to_excel(writer, sheet_name='Pivot Tables', index=False,
685
- startrow=len(dept_pivot) + len(mapping_pivot) + 6)
686
-
687
- # Write other sheets
688
- final_df.to_excel(writer, sheet_name='Final', index=False)
689
- data_df.to_excel(writer, sheet_name='Data', index=False)
690
- mapping_df.to_excel(writer, sheet_name='Mapping Reference', index=False)
691
-
692
- # Formatting
693
- workbook = writer.book
694
- pivot_sheet = workbook['Pivot Tables']
695
- blue_fill = PatternFill(start_color='1F77B4', end_color='1F77B4', fill_type='solid')
696
- white_font = Font(color='FFFFFF', bold=True)
697
-
698
- # Define pivot positions with their respective row count (data rows count, not including header row)
699
- pivot_positions = [
700
- (0, len(dept_pivot)), # Department pivot starting at row 0, with dept_pivot number of data rows
701
- (len(dept_pivot) + 3, len(mapping_pivot)), # Mapping pivot
702
- (len(dept_pivot) + len(mapping_pivot) + 6, len(service_pivot)) # Service pivot
703
- ]
704
-
705
- # Format each pivot section (headers and Grand Total rows)
706
- for start_row, pivot_length in pivot_positions:
707
- # Format header row (Excel row: start_row+1)
708
- for col in [1, 2]:
709
- cell = pivot_sheet.cell(row=start_row + 1, column=col)
710
- cell.fill = blue_fill
711
- cell.font = white_font
712
-
713
- # Format Grand Total row within the pivot table data
714
- # The data rows start at row start_row+2 up to row start_row+pivot_length+1 (inclusive)
715
- for row_idx in range(start_row + 2, start_row + pivot_length + 2):
716
- if pivot_sheet.cell(row=row_idx, column=1).value == 'Grand Total':
717
- for col in [1, 2]:
718
- cell = pivot_sheet.cell(row=row_idx, column=col)
719
- cell.fill = blue_fill
720
- cell.font = white_font
721
-
722
-
723
- # Apply Indian number formatting for integers
724
- indian_number_format = '#,##,##0' # The '0' ensures no decimal places
725
-
726
- # Department pivot table
727
- for row_idx in range(2, len(dept_pivot) + 2):
728
- cell = pivot_sheet.cell(row=row_idx, column=2)
729
- cell.number_format = indian_number_format
730
-
731
- # Mapping pivot table
732
- mapping_header_row = len(dept_pivot) + 4
733
- for row_idx in range(mapping_header_row + 1, mapping_header_row + len(mapping_pivot) + 1):
734
- cell = pivot_sheet.cell(row=row_idx, column=2)
735
- cell.number_format = indian_number_format
736
-
737
- # Service pivot table
738
- service_header_row = len(dept_pivot) + len(mapping_pivot) + 7
739
- for row_idx in range(service_header_row + 1, service_header_row + len(service_pivot) + 1):
740
- cell = pivot_sheet.cell(row=row_idx, column=2)
741
- cell.number_format = indian_number_format
742
-
743
- # Adjust column widths
744
- for col in [1, 2]:
745
- col_letter = get_column_letter(col)
746
- pivot_sheet.column_dimensions[col_letter].width = 25
747
-
748
- print("Processing completed successfully!")
749
- return True
750
-
751
- except Exception as e:
752
- print(f"Error: {e}")
753
- import traceback
754
- traceback.print_exc()
755
- return False
756
-
757
- # Add to imports
758
- import tempfile
759
- import shutil
760
-
761
- def process_health_studio(input_file_path, current_month, current_year):
762
- """End-to-end processing for Health Studio SBU"""
763
- try:
764
- # Create temporary workspace
765
- with tempfile.TemporaryDirectory() as tmpdir:
766
- # Step 1: Convert HTML to Excel
767
- intermediate1 = os.path.join(tmpdir, "processed_hospital_report.xlsx")
768
- convert_html_to_excel(input_file_path, intermediate1)
769
-
770
- # Step 2: Preprocess data
771
- intermediate2 = os.path.join(tmpdir, "processed_hospital_revenue_billing.xlsx")
772
- if not preprocess_hospital_revenue(intermediate1, intermediate2):
773
- raise RuntimeError("Data preprocessing failed")
774
-
775
- # Step 3: Create final output with pivots
776
- final_output = os.path.join(tmpdir, "health_studio_revenue_with_pivots.xlsx")
777
-
778
- # Get the directory of the current script (Variable folder)
779
- current_dir = Path(__file__).parent.resolve()
780
-
781
- # Construct the full path to the config file
782
- mapping_path = current_dir / "Mapping.xlsx"
783
-
784
- if not map_billing_categories_and_create_pivots(intermediate2, mapping_path, # Ensure this file exists in working directory
785
- final_output):
786
- raise RuntimeError("Pivot table creation failed")
787
-
788
- # Copy final output from tmpdir to a permanent location
789
- permanent_output = os.path.join(os.getcwd(), f'Health_Studio_Cleaned_RR-{current_month}-{current_year}.xlsx')
790
- shutil.copy(final_output, permanent_output)
791
- return permanent_output
792
-
793
- except Exception as e:
794
- print(f"Maatri processing error: {str(e)}")
795
- return None
796
-
797
- if __name__ == "__main__":
798
- # test the module
799
- sample_file_path = "/content/print_hospital_revenue_report.php (4).xls" # or the appropriate sample file path
800
- current_month = "Feb"
801
- current_year = "25"
802
- result = process_health_studio(sample_file_path, current_month, current_year)
803
- if result:
804
- print("Processing was successful:", result)
805
- else:
806
- print("Processing failed.")
807
-