Spaces:
Sleeping
Sleeping
File size: 66,058 Bytes
34a733e | 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 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 | # -*- coding: utf-8 -*-
"""Ortho_Variable_Final.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/19RxJ59AahlxwVEU5Hojudmm4owISTrZ7
"""
"""
HTML to Excel Converter for Hospital Revenue Report (Stable Version)
"""
import pandas as pd
from bs4 import BeautifulSoup
import os
def convert_html_to_excel(input_file, output_file):
# 1. Read the HTML file with verification
print(f"\n[1/6] Reading HTML file: {os.path.basename(input_file)}")
with open(input_file, 'r', encoding='utf-8', errors='ignore') as f:
html_content = f.read()
print("✓ File read successfully")
# 2. Parse HTML with lxml for consistency
print("[2/6] Parsing HTML content...")
soup = BeautifulSoup(html_content, 'lxml')
tables = soup.find_all('table')
print(f"✓ Found {len(tables)} tables in document")
# 3. Identify main table by headers
print("[3/6] Locating main data table...")
expected_headers = ['Sr.\xa0No.'] # UPDATE THESE
main_table = None
for i, table in enumerate(tables):
first_row = table.find('tr')
if first_row:
headers = [th.get_text(strip=True) for th in first_row.find_all(['th', 'td'])]
if all(h in headers for h in expected_headers):
main_table = table
print(f"✓ Identified table {i+1} as main data table")
print(f" Table dimensions: {len(table.find_all('tr'))} rows")
break
if not main_table:
raise ValueError("× ERROR: Could not find main data table with expected headers")
# 4. Extract and validate data rows
print("[4/6] Processing table rows...")
rows = main_table.find_all('tr')
header_row = rows[0]
headers = [col.get_text(strip=True) for col in header_row.find_all(['th', 'td'])]
valid_col_count = len(headers)
print(f"✓ Header row identified with {valid_col_count} columns:")
print(f" {headers}")
print(f"✓ Processing {len(rows)-1} data rows...")
# Process data rows with validation
data = []
skipped_rows = 0
for i, row in enumerate(rows[1:]): # Skip header
cols = row.find_all(['td', 'th'])
if len(cols) != valid_col_count:
skipped_rows += 1
continue
data.append([col.get_text(strip=True) for col in cols])
print(f"✓ Clean rows extracted: {len(data)}")
print(f" Skipped {skipped_rows} malformed rows")
# [5/6] Total Row Removal (Guaranteed Last Row + "Total Net Amount" Check)
print("[5/6] Checking for total row...")
if data:
last_row = data[-1]
# Check if "total net amount" exists in ANY cell of the last row
if any("total net amount" in cell.lower() for cell in last_row):
print("✓ Removed TOTAL NET AMOUNT row")
data = data[:-1]
print(f"✓ Final data rows: {len(data)}")
# 6. Create and save DataFrame
print("[6/6] Creating Excel file...")
df = pd.DataFrame(data, columns=headers)
# Final verification
print(f"✓ DataFrame created with dimensions: {df.shape}")
print(f"✓ First 3 columns: {df.columns.tolist()[:3]}...")
print(f"✓ Last 3 columns: {df.columns.tolist()[-3:]}...")
df.to_excel(output_file, index=False)
print(f"\nProcessing complete! Saved to: {output_file}")
print(f"Final verification:")
print(f"- Total rows: {len(df):,}")
print(f"- Total columns: {len(df.columns):,}")
return output_file
def process_multiple_files(file_list):
"""
Process multiple HTML files and convert them to Excel.
Args:
file_list: List of input HTML filenames to process
"""
print(f"Starting batch processing of {len(file_list)} files...")
results = []
for i, input_file in enumerate(file_list):
print(f"\n[File {i+1}/{len(file_list)}] Processing: {input_file}")
# Extract base name for output file
base_name = os.path.splitext(os.path.basename(input_file))[0]
output_file = f"processed_{base_name}.xlsx"
try:
result = convert_html_to_excel(input_file, output_file)
results.append((input_file, result, "Success"))
except Exception as e:
print(f"× ERROR processing {input_file}: {str(e)}")
results.append((input_file, None, f"Error: {str(e)}"))
# Print summary
print("\n" + "="*50)
print("BATCH PROCESSING SUMMARY")
print("="*50)
for input_file, output_file, status in results:
print(f"{input_file} → {output_file if output_file else 'FAILED'} ({status})")
success_count = sum(1 for _, _, status in results if status == "Success")
print(f"\nProcessed {success_count}/{len(file_list)} files successfully")
return results
if __name__ == "__main__":
file_list = [
'/content/Doctor OT with package.xls',
'/content/Doctor OT without package.xls',
'/content/Doctor visit with package.xls',
'/content/Doctor visit without package.xls',
'/content/Rev Report.xls',
'/content/IP Bill register.xls',
'/content/GRN.xls'
]
process_multiple_files(file_list)
# OPD Processing Block
import pandas as pd
import re
def normalize_name(name):
name = re.sub(r'^dr[\.\s]*', '', str(name), flags=re.IGNORECASE)
name = re.sub(r'[^a-zA-Z0-9]', '', name)
return name.lower().strip()
def filter_patient_records(file_path, search_term):
df = pd.read_excel(file_path)
df['clean_name'] = df['Department'].apply(normalize_name)
search_clean = normalize_name(search_term)
filtered = df[
(df['Patient Type'] == 'OPD') &
(df['Service Type'] == 'Consultation') &
(df['clean_name'].str.contains(search_clean, regex=False, na=False))
]
return filtered.drop(columns=['clean_name'])
if __name__ == "__main__":
excel_file = "/content/processed_print_hospital_revenue_report.php.xlsx"
search = 'Orthopaedics'
output_file = 'processed_opd_consultations.xlsx'
results = filter_patient_records(excel_file, search)
if not results.empty:
results.to_excel(output_file, index=False)
print(f"\nFound {len(results)} matches:")
print(results[['Date', 'Patient Name', 'Name', 'Department', 'Service Name', 'Net Amount']])
else:
print("\nNo matches found")
'''
import pandas as pd
df= pd.read_excel('/content/processed_doctor_visit_report_with_package.xlsx')
df2= pd.read_excel('/content/processed_doctor_visit_report_without_package.xlsx')
base_name = 'processed_doctor_visit_report'
df['Type']='Package'
df2['Type']='Open'
# assume df has shape (1420, 13) & df2 hs shape (3635, 13)
df_final = pd.concat([df, df2], axis=0, ignore_index=True)
print(df_final.shape)
df_final.to_excel(f'final_{base_name}.xlsx', index=False)
'''
#df_cross= pd.read_excel('/content/processed_print_inpatient_bill_register_report.xlsx')
import pandas as pd
import re
def normalize_doctor_name(name):
"""Hospital-standard cleaning logic (recommended version)"""
name = re.sub(r'\(.*?\)', '', str(name))
name = re.sub(r'^dr[.\s]*', '', name, flags=re.IGNORECASE)
name = re.sub(r'[^a-zA-Z]', '', name)
return name.lower().strip()
def process_reports(doctor_input, file1_path, file2_path):
df1 = pd.read_excel(file1_path)
df2 = pd.read_excel(file2_path)
norm_input = normalize_doctor_name(doctor_input)
df1['clean_doctor'] = df1['Doctor Name'].apply(normalize_doctor_name)
df2['clean_doctor'] = df2['Admiting Doctor'].apply(normalize_doctor_name)
filtered_df2 = df2[df2['clean_doctor'] == norm_input]
admission_numbers = filtered_df2['Admission No.'].unique().tolist()
df1['Consultation Type'] = pd.NA
doctor_mask = df1['clean_doctor'] == norm_input
admission_mask = df1['Admission No.'].isin(admission_numbers)
df1.loc[doctor_mask & admission_mask, 'Consultation Type'] = 'Self'
df1.loc[doctor_mask & ~admission_mask, 'Consultation Type'] = 'Cross'
df1.drop(columns=['clean_doctor'], inplace=True)
stats = {
'Total Records': len(df1),
'Target Doctor Records': doctor_mask.sum(),
'Self Consultations': (doctor_mask & admission_mask).sum(),
'Cross Consultations': (doctor_mask & ~admission_mask).sum(),
'Untagged Records': len(df1) - doctor_mask.sum()
}
return df1, stats
def main():
df = pd.read_excel('final_processed_doctor_visit_report.xlsx')
df2 = pd.read_excel('processed_print_inpatient_bill_register_report.xlsx')
df['Consultation Type'] = pd.NA
doctors = [
'Dr. Nishikant Kumar',
'Dr. GURUDEO KUMAR',
'Dr Ramit Gunjan',
'Dr SAURABH CHAUDHARY'
]
for doctor_name in doctors:
norm_input = normalize_doctor_name(doctor_name)
admissions = (
df2[df2['Admiting Doctor']
.map(normalize_doctor_name) == norm_input]
['Admission No.']
.unique()
)
mask_doc = df['Doctor Name'].map(normalize_doctor_name) == norm_input
mask_adm = df['Admission No.'].isin(admissions)
df.loc[mask_doc & mask_adm, 'Consultation Type'] = 'Self'
df.loc[mask_doc & ~mask_adm, 'Consultation Type'] = 'Cross'
total = len(df)
target_cnt = int(mask_doc.sum())
self_cnt = int((mask_doc & mask_adm).sum())
cross_cnt = int((mask_doc & ~mask_adm).sum())
untagged = total - target_cnt
print(f"\nProcessing Statistics:")
print(f"- Target Doctor: {doctor_name}")
print(f"- Total records processed: {total}")
print(f"- Target doctor's records: {target_cnt}")
print(f" ├─ Self consultations: {self_cnt}")
print(f" └─ Cross consultations: {cross_cnt}")
print(f"- Untagged records (other doctors): {untagged}")
output_file = 'precision_tagged_all_consultations.xlsx'
df.to_excel(output_file, index=False)
print(f"Saved combined filtered data for all doctors to: {output_file}")
if __name__ == "__main__":
main()
import pandas as pd
import re
def normalize_doctor_name(name: str) -> str:
"""Hospital‐standard cleaning logic."""
name = re.sub(r'\(.*?\)', '', str(name))
name = re.sub(r'^dr[.\s]*', '', name, flags=re.IGNORECASE)
name = re.sub(r'[^a-zA-Z]', '', name)
return name.lower().strip()
def get_self_open_records(
input_file: str,
doctor_list: list[str]
) -> pd.DataFrame:
"""
Load the tagged‐consultations Excel, and return only those rows
for the given doctors where Type == 'open' and Consultation Type == 'Self'.
"""
df = pd.read_excel(input_file)
norm_docs = { normalize_doctor_name(d) for d in doctor_list }
df['__clean_doc'] = df['Doctor Name'].map(normalize_doctor_name)
mask = (
df['__clean_doc'].isin(norm_docs) &
df['Type'].str.lower().eq('open') &
df['Consultation Type'].eq('Self')
)
result = df.loc[mask].copy()
result.drop(columns='__clean_doc', inplace=True)
return result
def main():
doctors = [
'Dr. Nishikant Kumar',
'Dr. GURUDEO KUMAR',
'Dr Ramit Gunjan',
'Dr SAURABH CHAUDHARY'
]
input_file = 'precision_tagged_all_consultations.xlsx'
output_file = 'self_open_for_doctors.xlsx'
filtered_df = get_self_open_records(input_file, doctors)
filtered_df.to_excel(output_file, index=False)
print(f"Extracted {len(filtered_df)} rows where Type='open' and Consultation Type='Self'")
print(f"Saved to: {output_file}")
if __name__ == "__main__":
main()
import pandas as pd
import re
def normalize_doctor_name(name: str) -> str:
"""Hospital‐standard cleaning logic."""
name = re.sub(r'\(.*?\)', '', str(name))
name = re.sub(r'^dr[.\s]*', '', name, flags=re.IGNORECASE)
name = re.sub(r'[^a-zA-Z]', '', name)
return name.lower().strip()
def get_cross_records(
input_file: str,
doctor_list: list[str]
) -> pd.DataFrame:
"""
Load the tagged‐consultations Excel, and return only those rows
for the given doctors where Consultation Type == 'Cross'.
"""
df = pd.read_excel(input_file)
norm_docs = { normalize_doctor_name(d) for d in doctor_list }
df['__clean_doc'] = df['Doctor Name'].map(normalize_doctor_name)
# 4) Filter:
# - row’s doctor is one of norm_docs
# - Consultation Type is exactly 'Cross'
mask = (
df['__clean_doc'].isin(norm_docs)
& df['Consultation Type'].eq('Cross')
)
result = df.loc[mask].copy()
result.drop(columns='__clean_doc', inplace=True)
return result
def main():
doctors = [
'Dr. Nishikant Kumar',
'Dr. GURUDEO KUMAR',
'Dr Ramit Gunjan',
'Dr SAURABH CHAUDHARY'
]
input_file = 'precision_tagged_all_consultations.xlsx'
output_file = 'cross_for_doctors.xlsx'
filtered_df = get_cross_records(input_file, doctors)
filtered_df.to_excel(output_file, index=False)
print(f"Extracted {len(filtered_df)} rows where Consultation Type='Cross'")
print(f"Saved to: {output_file}")
if __name__ == "__main__":
main()
'''
import pandas as pd
df= pd.read_excel('/content/processed_doctor_ot_with_package.xlsx')
df2= pd.read_excel('/content/processed_doctor_ot_without_package.xlsx')
base_name = 'processed_doctor_ot_report'
df['Type']='Package'
df2['Type']='Open'
# assume df has shape (1420, 13) & df2 has shape (3635, 13)
df_final = pd.concat([df, df2], axis=0, ignore_index=True)
print(df_final.shape)
df_final.to_excel(f'final_{base_name}.xlsx', index=False)
'''
# surgery_rev = pd.read_excel('/content/processed_print_inpatient_bill_register_report.xlsx')
# final for handling both surgery [package and open cases]
import pandas as pd
import re
import numpy as np
import warnings
# Suppress SettingWithCopyWarning
warnings.filterwarnings('ignore', category=pd.errors.SettingWithCopyWarning)
def normalize_doctor_name(name: str) -> str:
"""Hospital‐standard cleaning logic."""
if not isinstance(name, str):
name = str(name)
name = re.sub(r'\(.*?\)', '', name)
name = re.sub(r'^dr[.\s]*', '', name, flags=re.IGNORECASE)
name = re.sub(r'[^a-zA-Z]', '', name)
return name.lower().strip()
def process_surgeon_payouts(
ot_report_path: str,
bill_register_path: str,
doctor_list: list[str]
) -> None:
"""
Process surgeon payouts with enhanced debugging
"""
print("="*50)
print("STARTING PROCESSING")
print("="*50)
# Load data
print("\n[1/6] Loading reports...")
ot_df = pd.read_excel(ot_report_path)
bill_df = pd.read_excel(bill_register_path)
print(f"- OT report: {len(ot_df)} records")
print(f"- Billing register: {len(bill_df)} records")
# Normalize doctor names for filtering
print("\n[2/6] Filtering for specified doctors...")
norm_docs = {normalize_doctor_name(d) for d in doctor_list}
print(f"Target doctors (normalized): {', '.join(norm_docs)}")
# Filter OT report
ot_df['__clean_doc'] = ot_df['Doctor Name'].map(normalize_doctor_name)
ot_df = ot_df[ot_df['__clean_doc'].isin(norm_docs)].copy()
print(f"- OT report after filtering: {len(ot_df)} records")
# Filter billing register
bill_df['__clean_doc'] = bill_df['Admiting Doctor'].map(normalize_doctor_name)
bill_df = bill_df[bill_df['__clean_doc'].isin(norm_docs)].copy()
print(f"- Billing register after filtering: {len(bill_df)} records")
# Clean and convert numeric columns
print("\n[3/6] Processing financial data...")
# Clean OT 'Total' column (surgeon fee)
ot_df['Total'] = (
ot_df['Total']
.astype(str)
.str.replace(',', '')
.replace('nan', '0')
.astype(float)
)
print(f"- OT 'Total' column cleaned (min: ₹{ot_df['Total'].min():,.2f}, max: ₹{ot_df['Total'].max():,.2f})")
# Clean billing 'Net' column
bill_df['Net'] = (
bill_df['Net']
.astype(str)
.str.replace(',', '')
.replace('nan', '0')
.astype(float)
)
print(f"- Billing 'Net' column cleaned (min: ₹{bill_df['Net'].min():,.2f}, max: ₹{bill_df['Net'].max():,.2f})")
# Create Net Bill mapping
net_bill_map = bill_df.groupby('Admission No.')['Net'].first().to_dict()
ot_df['Net Bill'] = ot_df['Admission No.'].map(net_bill_map)
print(f"- Mapped net bills to {ot_df['Net Bill'].notna().sum()} OT records")
# Handle duplicates
print("\n[4/6] Handling duplicate admissions...")
found_mask = ot_df['Net Bill'].notna()
found_df = ot_df[found_mask].drop_duplicates(subset='Admission No.')
not_found_df = ot_df[~found_mask]
processed_ot = pd.concat([found_df, not_found_df])
print(f"- Unique admissions: {len(found_df)}")
print(f"- Records without billing: {len(not_found_df)}")
# Sort by date
print("\n[5/6] Calculating cumulative payouts...")
processed_ot['Date'] = pd.to_datetime(processed_ot['Date'], format='%d/%m/%Y', errors='coerce')
processed_ot = processed_ot.sort_values('Date')
print(f"- Sorted records from {processed_ot['Date'].min().date()} to {processed_ot['Date'].max().date()}")
# Calculate cumulative net bill and variable percentage
cumulative_net = 0
variable_rates = []
for idx, row in processed_ot.iterrows():
if pd.notna(row['Net Bill']):
cumulative_net += row['Net Bill']
if cumulative_net <= 15000000:
rate = 0.10
elif cumulative_net <= 20000000:
rate = 0.12
else:
rate = 0.15
variable_rates.append(rate)
else:
variable_rates.append(np.nan)
processed_ot['Variable'] = variable_rates
# CORRECTED: Calculate payout as Total (surgeon fee) * Variable rate
processed_ot['Net Payout'] = processed_ot['Total'] * processed_ot['Variable']
# Convert Net Payout to integers (round to nearest rupee)
processed_ot['Net Payout'] = processed_ot['Net Payout'].apply(
lambda x: round(x) if not pd.isna(x) else x
).astype('Int64') # Uses pandas' nullable integer type
print(f"- Final cumulative net: ₹{cumulative_net:,.2f}")
print(f"- Current variable rate: {variable_rates[-1]*100 if variable_rates and pd.notna(variable_rates[-1]) else 'N/A'}%")
# Split into Package and Open reports
print("\n[6/6] Splitting and saving reports...")
package_df = processed_ot[processed_ot['Type'] == 'Package'].copy()
open_df = processed_ot[processed_ot['Type'] == 'Open'].copy()
# Remove unwanted columns
unwanted_cols = [col for col in package_df.columns
if 'unnamed' in col.lower() or 'vlookup' in col.lower()]
if unwanted_cols:
print(f"- Removing unwanted columns: {', '.join(unwanted_cols)}")
package_df = package_df.drop(columns=unwanted_cols, errors='ignore')
open_df = open_df.drop(columns=unwanted_cols, errors='ignore')
# Clean up temporary columns safely
package_df = package_df.drop(columns=['__clean_doc'], errors='ignore')
open_df = open_df.drop(columns=['__clean_doc'], errors='ignore')
# Save results
package_df.to_excel('package_records.xlsx', index=False)
open_df.to_excel('open_records.xlsx', index=False)
print("\n" + "="*50)
print("PROCESSING COMPLETE")
print("="*50)
print(f"Package surgeries: {len(package_df)} rows")
print(f"- Total payout: ₹{package_df['Net Payout'].sum():,.0f}")
print(f"Open surgeries: {len(open_df)} rows")
print(f"- Total payout: ₹{open_df['Net Payout'].sum():,.0f}")
print(f"\nReports saved:")
print(f"- package_records.xlsx")
print(f"- open_records.xlsx")
print("\nNet Payout values converted to integers (rounded to nearest rupee)")
print(f"Removed {len(unwanted_cols)} unwanted columns from final reports")
def main():
# Define doctors
doctors = [
'Dr. Nishikant Kumar',
'Dr. GURUDEO KUMAR',
'Dr Ramit Gunjan',
'Dr SAURABH CHAUDHARY'
]
# File paths
ot_report_path = '/content/final_processed_doctor_ot_report.xlsx'
bill_register_path = '/content/processed_print_inpatient_bill_register_report.xlsx'
print("Starting surgeon payout processing...")
print(f"OT report: {ot_report_path}")
print(f"Billing register: {bill_register_path}")
print(f"Doctors: {', '.join(doctors)}")
# Process data
process_surgeon_payouts(
ot_report_path=ot_report_path,
bill_register_path=bill_register_path,
doctor_list=doctors
)
if __name__ == "__main__":
main()
import pandas as pd
from bs4 import BeautifulSoup
import os
def convert_html_to_excel_with_separator(input_file, output_file):
print(f"\n[1/6] Reading HTML file: {os.path.basename(input_file)}")
with open(input_file, 'r', encoding='utf-8', errors='ignore') as f:
html_content = f.read()
print("✓ File read successfully")
print("[2/6] Parsing HTML content...")
soup = BeautifulSoup(html_content, 'lxml')
tables = soup.find_all('table')
print(f"✓ Found {len(tables)} tables in document")
print("[3/6] Locating main data table...")
expected_headers = ['Sr.\xa0No.']
main_table = None
for i, table in enumerate(tables):
first_row = table.find('tr')
if first_row:
headers = [th.get_text(strip=True) for th in first_row.find_all(['th', 'td'])]
if all(h in headers for h in expected_headers):
main_table = table
print(f"✓ Identified table {i+1} as main data table")
break
if not main_table:
raise ValueError("× ERROR: Could not find main data table")
print("[4/6] Processing all rows...")
rows = main_table.find_all('tr')
headers = [col.get_text(strip=True) for col in rows[0].find_all(['th', 'td'])]
valid_col_count = len(headers)
rows_data = []
for row in rows[1:]:
cols = row.find_all(['td', 'th'])
cell_texts = [col.get_text(strip=True) for col in cols]
is_valid = len(cols) == valid_col_count
rows_data.append({'cells': cell_texts, 'valid': is_valid})
print(f"✓ Collected {len(rows_data)} rows (including invalid)")
print("[5/6] Detecting separation point...")
SPLIT_KEYWORD = 'IP Sales Return'
split_index = None
for idx, row_data in enumerate(rows_data):
if any(SPLIT_KEYWORD.lower() in cell.lower() for cell in row_data['cells']):
split_index = idx
print(f"✓ Split marker found at index {idx}")
break
if split_index is not None:
section1 = [row['cells'] for row in rows_data[:split_index] if row['valid']]
section2 = [row['cells'] for row in rows_data[split_index:] if row['valid']]
# Explicit separator row with visible text
blank_row = ['---- SEPARATOR ----'] * len(headers)
processed_data = section1 + [blank_row] + section2
print(f"✓ Sections: {len(section1)} + 1 (separator) + {len(section2)}")
else:
processed_data = [row['cells'] for row in rows_data if row['valid']]
print("× No split marker found")
print("[6/6] Saving to Excel...")
df = pd.DataFrame(processed_data, columns=headers)
df.to_excel(output_file, index=False)
print(f"\n✓ Done! File: {output_file}")
print(f"Total Rows: {len(df)} | Columns: {len(df.columns)}")
if __name__ == "__main__":
input_file = '/content/drive/MyDrive/Var Auto May/print_item_sale_report.xls'
output_file = f"processed_{os.path.splitext(os.path.basename(input_file))[0]}.xlsx"
convert_html_to_excel_with_separator(input_file, output_file)
# correct one
import pandas as pd
import re
def process_excel_with_separator(input_file, output_file):
df = pd.read_excel(input_file, dtype=str)
sep_mask = df.apply(
lambda row: row.astype(str)
.str.contains(r'---- SEPARATOR ----', na=False)
.any(),
axis=1
)
if not sep_mask.any():
raise ValueError("Separator row not found in the Excel file")
sep_idx = sep_mask.idxmax()
before = df.iloc[:sep_idx].copy()
separator = df.iloc[[sep_idx]].copy() # keep exactly as is
after = df.iloc[sep_idx + 1:].copy()
# 4. Determine which cols to flip (R→Y) plus ensure 'Profit' is included
flip_cols = after.columns[17:25].tolist()
if 'Profit' in after.columns and 'Profit' not in flip_cols:
flip_cols.append('Profit')
# 5. Clean & convert those cols in the “after” block, then *–1
for col in flip_cols:
after[col] = (
pd.to_numeric(
after[col]
.astype(str)
.str.replace(r'[₹,]', '', regex=True),
errors='coerce'
)
.mul(-1)
)
# 6. Also convert 'Profit' in the “before” block so sum is accurate
if 'Profit' in before.columns:
before['Profit'] = pd.to_numeric(
before['Profit']
.astype(str)
.str.replace(r'[₹,]', '', regex=True),
errors='coerce'
)
# concatenating after accounting return parts
final_df = pd.concat([before, separator, after], ignore_index=True)
final_df.to_excel(output_file, index=False)
# 9. Compute total profit (strip any remaining symbols, coerce any non-numbers to NaN)
total_profit = pd.to_numeric(
final_df['Profit']
.astype(str)
.str.replace(r'[₹,]', '', regex=True),
errors='coerce'
).sum()
return output_file, round(total_profit, 2)
if __name__ == "__main__":
inp = "/content/processed_print_item_sale_report.xlsx"
outp = "final_modified_report.xlsx"
result_file, total_profit = process_excel_with_separator(inp, outp)
print(f"Successfully processed file saved to: {result_file}")
print(f"Total Profit after adjustment: ₹ {total_profit:,.2f}")
#final code
import pandas as pd
import numpy as np
import re
from openpyxl import load_workbook
import warnings
warnings.filterwarnings('ignore', category=UserWarning, module='openpyxl')
def clean_numeric(value):
"""Convert various numeric formats to float, handling negatives and currency symbols"""
if isinstance(value, (int, float)):
return float(value)
if not isinstance(value, str):
return np.nan
# Remove currency symbols, commas, and extra spaces
cleaned = re.sub(r'[₹, ]', '', value.strip())
# Handle negative numbers in parentheses
if cleaned.startswith('(') and cleaned.endswith(')'):
cleaned = '-' + cleaned[1:-1]
# Handle empty strings
if cleaned in ['', '-']:
return np.nan
try:
return float(cleaned)
except ValueError:
return np.nan
def preprocess_item_name(name):
"""Normalize item names for case-insensitive matching"""
if pd.isna(name):
return ''
return re.sub(r'\s+', '', str(name)).lower()
def process_reports(final_report_path, grn_report_path, output_path):
"""
Process medical reports with all requirements:
1. Calculate taxes using GRN report
2. Mark unmatched items as "Not Found"
3. Convert columns Q to Y to float
4. Remove separator rows
5. Filter for Orthopaedics doctors
6. Remove Ayushman Bharat rows
7. Add Net Profit column (Profit - Tax, treating 'Not Found' as 0)
"""
# Read final report
final_df = pd.read_excel(final_report_path, sheet_name='Sheet1')
# Remove separator rows
final_df = final_df[~final_df.iloc[:, 0].astype(str).str.contains('---- SEPARATOR ----')]
# Convert columns Q to Y to float
cols_to_convert = [
'Qty', 'Rate', 'Total Rate', 'MRP', 'Total Amt',
'Discount', 'Profit', 'Total GST', 'Net Amt.'
]
for col in cols_to_convert:
if col in final_df.columns:
final_df[col] = final_df[col].apply(clean_numeric)
# Read GRN report
grn_df = pd.read_excel(grn_report_path)
# Clean numeric columns in GRN report
grn_df['Qty. Total'] = grn_df['Qty. Total'].apply(clean_numeric)
grn_df['CGST Amt'] = grn_df['CGST Amt'].apply(clean_numeric)
grn_df['SGST Amt'] = grn_df['SGST Amt'].apply(clean_numeric)
# Calculate tax per unit in GRN report
grn_df['Tax per Unit'] = np.where(
grn_df['Qty. Total'] > 0,
(grn_df['CGST Amt'] + grn_df['SGST Amt']) / grn_df['Qty. Total'],
np.nan
)
# Normalize item names in GRN report
grn_df['Normalized Item'] = grn_df['Item Name'].apply(preprocess_item_name)
# Get highest tax per unit for each item
max_tax_df = grn_df.groupby('Normalized Item')['Tax per Unit'].max().reset_index()
# Prepare final report for tax calculation
final_df['Normalized Item'] = final_df['Item Name'].apply(preprocess_item_name)
# Merge with tax data
final_df = pd.merge(
final_df,
max_tax_df,
on='Normalized Item',
how='left'
)
# Calculate tax amount or mark as Not Found
final_df['Tax'] = np.where(
pd.isna(final_df['Tax per Unit']),
"Not Found",
final_df['Tax per Unit'] * final_df['Qty']
)
# Create a numeric version of Tax for calculations
final_df['Tax Numeric'] = final_df['Tax'].apply(
lambda x: 0.0 if x == "Not Found" else float(x)
)
# Ensure Profit is float and calculate Net Profit
final_df['Profit'] = final_df['Profit'].astype(float)
final_df['Net Profit'] = final_df['Profit'] - final_df['Tax Numeric']
# Clean up intermediate columns
final_df = final_df.drop(columns=['Normalized Item', 'Tax per Unit', 'Tax Numeric'])
# Apply filters
# 1. Filter for Orthopaedics doctors (case-insensitive)
ortho_mask = final_df['Doctor Name'].str.contains('ortho', case=False, na=False)
# 2. Remove Ayushman Bharat rows (case-insensitive)
ayushman_mask = final_df['TPA/Corporate Name'].str.strip().str.lower() == 'ayushman bharat'
filtered_df = final_df[ortho_mask & ~ayushman_mask]
# Save to new Excel file
filtered_df.to_excel(output_path, index=False)
# Format the output Excel for currency
try:
wb = load_workbook(output_path)
ws = wb.active
# Format currency columns (including new Net Profit column)
currency_columns = [
'Rate', 'Total Rate', 'MRP', 'Total Amt', 'Discount',
'Profit', 'Total GST', 'Net Amt.', 'Net Profit'
]
for col in currency_columns:
if col in filtered_df.columns:
col_idx = filtered_df.columns.get_loc(col) + 1
for row in range(2, ws.max_row + 1):
cell = ws.cell(row=row, column=col_idx)
if isinstance(cell.value, (int, float)):
cell.number_format = '#,##0.00'
# Format Tax column for numeric values
if 'Tax' in filtered_df.columns:
tax_col_idx = filtered_df.columns.get_loc('Tax') + 1
for row in range(2, ws.max_row + 1):
cell = ws.cell(row=row, column=tax_col_idx)
if isinstance(cell.value, (int, float)):
cell.number_format = '#,##0.00'
wb.save(output_path)
except Exception as e:
print(f"Note: Formatting skipped - {str(e)}")
# Example usage
if __name__ == "__main__":
process_reports(
final_report_path='/content/final_modified_report.xlsx',
grn_report_path='/content/processed_print_grn_details_report.xlsx',
output_path='orthopaedic_report_with_tax.xlsx'
)
print("Processing complete! Filtered report saved to 'orthopaedic_report_with_tax.xlsx'")
import pandas as pd
import re
def normalize_name(name: str) -> str:
"""Clean doctor names for robust matching."""
name = re.sub(r'^dr[\.\s]*', '', str(name), flags=re.IGNORECASE)
name = re.sub(r'[^a-zA-Z0-9]', '', name)
return name.lower().strip()
def filter_extra_implant_charges(
file_path: str
) -> tuple[pd.DataFrame, int]:
"""
Load the hospital revenue report Excel and return:
- filtered DataFrame where
Service Type == 'Other Charges'
Service Name contains 'Extra Implant' (case-insensitive)
Department == 'Orthopaedics' (case-insensitive)
- the number of unique UHID in that filtered set
"""
# 1) Read the report
df = pd.read_excel(file_path)
# 2) Build masks
mask_type = df['Service Type'].str.strip().eq('Other Charges')
mask_name = df['Service Name']\
.fillna('')\
.str.contains(r'extra\s*implant', flags=re.IGNORECASE, regex=True)
mask_dept = df['Department']\
.fillna('')\
.str.strip()\
.str.lower()\
.eq('orthopaedics')
# 3) Apply filters
filtered = df[mask_type & mask_name & mask_dept].copy()
# 4) Compute unique UHID count
unique_uhid_count = filtered['UHID'].nunique()
return filtered, unique_uhid_count
if __name__ == "__main__":
excel_file = "/content/processed_print_hospital_revenue_report.php.xlsx"
output_file = "extra_implant_orthopaedics.xlsx"
filtered_df, uhid_count = filter_extra_implant_charges(excel_file)
if not filtered_df.empty:
filtered_df.to_excel(output_file, index=False)
print(f"Saved {output_file} with filtered records.")
print(f"Found {len(filtered_df)} matching records.")
print(f"Unique UHID count: {uhid_count}")
print(filtered_df[['Date', 'Patient Name', 'Department',
'Service Type', 'Service Name', 'Net Amount', 'UHID']])
else:
print("No matching records found.")
# Diag, Path and Daycare Reports
import pandas as pd
import re
def normalize_name(name):
"""Clean department names for robust matching"""
if pd.isna(name) or name == '':
return ''
# Remove all non-alphanumeric characters and spaces
name = re.sub(r'[^a-zA-Z0-9]', '', str(name))
return name.lower().strip()
def generate_ortho_service_report(file_path, service_type, output_file):
"""
Generate a report of specific services for patients who had OPD consultations
in the Orthopaedics department.
Steps:
1. Filter records where Patient Type is OPD and Department is Orthopaedics
2. Extract all unique UHID values from these filtered records
3. From all records (unfiltered), select those where:
- Service Type matches the specified service_type
- Department is either Orthopaedics or blank
- UHID matches one from the list in step 2
- Patient Type is OPD
4. Save these final records to a report
"""
df = pd.read_excel(file_path)
df['clean_department'] = df['Department'].apply(normalize_name)
ortho_clean = normalize_name('Orthopaedics')
opd_mask = df['Patient Type'] == 'OPD'
ortho_mask = df['clean_department'].str.contains(ortho_clean, regex=False, na=False)
opd_ortho_mask = opd_mask & ortho_mask
opd_ortho_records = df[opd_ortho_mask]
unique_uhids = opd_ortho_records['UHID'].unique()
uhid_mask = df['UHID'].isin(unique_uhids)
service_mask = df['Service Type'] == service_type
dept_mask = (
df['clean_department'].str.contains(ortho_clean, regex=False, na=False) |
df['Department'].isna() |
(df['Department'] == '')
)
opd_mask_final = df['Patient Type'] == 'OPD'
final_mask = uhid_mask & service_mask & dept_mask & opd_mask_final
service_records = df[final_mask]
service_records = service_records.drop(columns=['clean_department'])
if not service_records.empty:
service_records.to_excel(output_file, index=False)
return service_records
if __name__ == "__main__":
excel_file = "/content/processed_print_hospital_revenue_report.php.xlsx"
# Rep for Diag
diagnostic_output = 'ortho_opd_diagnostics.xlsx'
diagnostic_results = generate_ortho_service_report(excel_file, 'Diagnostic', diagnostic_output)
# Rep for Path
pathology_output = 'ortho_opd_pathology.xlsx'
pathology_results = generate_ortho_service_report(excel_file, 'Pathology', pathology_output)
# Rep for Day Care
daycare_output = 'ortho_opd_daycare.xlsx'
daycare_results = generate_ortho_service_report(excel_file, 'Day Care Procedure', daycare_output)
print("All reports generated successfully:")
print(f"1. Diagnostic services: {len(diagnostic_results)} records")
print(f"2. Pathology services: {len(pathology_results)} records")
print(f"3. Day Care Procedure services: {len(daycare_results)} records")
# final updated code
import pandas as pd
import openpyxl
from openpyxl.styles import PatternFill, Border, Side, Alignment, Font
import os
import datetime
# Define the current month and year
current_month = "May"
current_year = "2025"
# Helper function to clean numeric strings and convert to float
def clean_and_convert_to_float(value):
if isinstance(value, (int, float)):
return float(value)
elif isinstance(value, str):
# Remove currency symbols, commas, and other non-numeric characters
# Keep decimal points and negative signs
cleaned = ''.join(c for c in value if c.isdigit() or c in '.-')
try:
return float(cleaned)
except ValueError:
return 0.0
else:
return 0.0
# for summary sheet
def create_summary_sheet(workbook, data_dir, current_month, current_year):
summary_sheet = workbook.create_sheet("Summary", 0)
header_fill = PatternFill(start_color="92D050", end_color="92D050", fill_type="solid")
subheader_fill = PatternFill(start_color="B8CCE4", end_color="B8CCE4", fill_type="solid")
thin_border = Side(border_style="thin", color="000000")
border = Border(top=thin_border, left=thin_border, right=thin_border, bottom=thin_border)
header_font = Font(bold=True, color="FFFFFF", size=13)
subheader_font = Font(bold=True, size=12)
data_font = Font(size=11)
center_alignment = Alignment(horizontal="center", vertical="center")
left_alignment = Alignment(horizontal="left", vertical="center")
right_alignment = Alignment(horizontal="right", vertical="center")
# Set column widths
summary_sheet.column_dimensions["A"].width = 5
summary_sheet.column_dimensions["B"].width = 45
summary_sheet.column_dimensions["C"].width = 15
summary_sheet.column_dimensions["D"].width = 15
summary_sheet.column_dimensions["E"].width = 15
# Add title row
summary_sheet.merge_cells("B2:E2")
title_cell = summary_sheet["B2"]
title_cell.value = f"Orthopedics Department Variable Payout Summary - {current_month} {current_year}"
title_cell.fill = header_fill
title_cell.font = header_font
title_cell.alignment = center_alignment
# Add column headers
summary_sheet["B3"] = "Services"
summary_sheet["C3"] = "Total Sum"
summary_sheet["D3"] = "Variable Share"
summary_sheet["E3"] = "Final Share"
for col in ["B", "C", "D", "E"]:
cell = summary_sheet[f"{col}3"]
cell.fill = subheader_fill
cell.font = subheader_font
cell.alignment = center_alignment
cell.border = border
package_file = os.path.join(data_dir, "package_records.xlsx")
open_file = os.path.join(data_dir, "open_records.xlsx")
df_package = pd.read_excel(package_file)
package_count = len(df_package)
df_open = pd.read_excel(open_file)
open_count = len(df_open)
total_surgeries = package_count + open_count
# Define the rows for the summary sheet
summary_rows = [
{"service": "OPD Consultation", "file": "processed_opd_consultations.xlsx", "variable_share": 0.60},
{"service": "IPD Consultation (Non-Package)", "file": "self_open_for_doctors.xlsx", "variable_share": 0.20},
{"service": "IPD Cross Consultation", "file": "cross_for_doctors.xlsx", "variable_share": 0.20},
{"service": f"Surgeries (Total {total_surgeries} Surgeries in {current_month} 2025)", "file": None, "variable_share": None},
{"service": " Surgery (Package cases)", "file": "package_records.xlsx", "variable_share": "hardcoded_d8"},
{"service": " Surgery (Open cases)", "file": "open_records.xlsx", "variable_share": "hardcoded_d9"},
{"service": "Pathology", "file": "ortho_opd_pathology.xlsx", "variable_share": 0.10},
{"service": "Diagnostics", "file": "ortho_opd_diagnostics.xlsx", "variable_share": 0.10},
{"service": "Daycare Procedure", "file": "ortho_opd_daycare.xlsx", "variable_share": 0.20},
{"service": "Implant", "file": "orthopaedic_report_with_tax.xlsx", "variable_share": 0.50},
{"service": "Extra Cash Variable for AB Patients (Only Extra Part)", "file": "extra_implant_orthopaedics.xlsx", "variable_share": 30000, "no_currency": True}
]
# Add data rows
row_num = 4
for row_data in summary_rows:
summary_sheet[f"B{row_num}"] = row_data["service"]
# Apply styling to individual cells
for col in ["B", "C", "D", "E"]:
cell = summary_sheet[f"{col}{row_num}"]
cell.border = border
cell.font = data_font
if col == "B":
cell.alignment = left_alignment
else:
cell.alignment = right_alignment
row_num += 1
# Add total and additional rows
total_row = row_num
summary_sheet[f"B{row_num}"] = f"Total Variable for {current_month}-{current_year}"
summary_sheet[f"B{row_num}"].font = Font(bold=True, size=11)
row_num += 1
summary_sheet[f"B{row_num}"] = "Add: Previous Bills Realised from TPAs/Corporates"
summary_sheet[f"B{row_num}"].font = Font(size=11)
row_num += 1
summary_sheet[f"B{row_num}"] = f"Less: TPA/Corporate Dues for {current_month}-{current_year}"
summary_sheet[f"B{row_num}"].font = Font(size=11)
row_num += 1
summary_sheet[f"B{row_num}"] = "Less: Professional Fee for Dr. Gurudeo"
summary_sheet[f"B{row_num}"].font = Font(size=11)
row_num += 1
summary_sheet[f"B{row_num}"] = f"Variable Payable for {current_month}-{current_year}"
summary_sheet[f"B{row_num}"].font = Font(bold=True, size=11)
row_num += 1
summary_sheet[f"B{row_num}"] = "Less: TDS @ 10%"
summary_sheet[f"B{row_num}"].font = Font(size=11)
row_num += 1
net_payable_row = row_num
summary_sheet[f"B{row_num}"] = f"Net Payable for {current_month}-{current_year}"
summary_sheet[f"B{row_num}"].font = Font(bold=True, size=11)
# Highlight the net payable row with yellow color
yellow_fill = PatternFill(start_color="FFFF00", end_color="FFFF00", fill_type="solid")
for col in ["B", "C", "D", "E"]:
summary_sheet[f"{col}{net_payable_row}"].fill = yellow_fill
# Apply borders to all additional rows
for r in range(total_row, row_num + 1):
for col in ["B", "C", "D", "E"]:
cell = summary_sheet[f"{col}{r}"]
cell.border = border
if col != "B":
cell.alignment = right_alignment
return summary_sheet, summary_rows
# Function to populate the summary sheet with data
def populate_summary_data(summary_sheet, summary_rows, data_dir, current_month, current_year):
# Dictionary to store the total sums for each service
total_sums = {}
# Process each row in the summary
row_num = 4
for row_data in summary_rows:
service = row_data["service"]
file = row_data["file"]
variable_share = row_data["variable_share"]
if file and os.path.exists(os.path.join(data_dir, file)):
df = pd.read_excel(os.path.join(data_dir, file))
# Calculate total sum based on the file type
if file == "processed_opd_consultations.xlsx":
# Clean and convert Net Amount column if it exists
if "Net Amount" in df.columns:
df["Net Amount"] = df["Net Amount"].apply(clean_and_convert_to_float)
total_sum = df["Net Amount"].sum()
elif file in ["self_open_for_doctors.xlsx", "cross_for_doctors.xlsx"]:
# Clean and convert Total column
if "Total" in df.columns:
df["Total"] = df["Total"].apply(clean_and_convert_to_float)
total_sum = df["Total"].sum()
elif file == "package_records.xlsx":
# Clean and convert Total column
if "Total" in df.columns:
df["Total"] = df["Total"].apply(clean_and_convert_to_float)
total_sum = df["Total"].sum()
else:
total_sum = 0
# For D8, hardcode the value and populate E8 with sum of 'Net Payout'
summary_sheet[f"D{row_num}"] = "10/12/15%"
summary_sheet[f"D{row_num}"].number_format = '@'
if "Net Payout" in df.columns:
df["Net Payout"] = df["Net Payout"].apply(clean_and_convert_to_float)
final_share = df["Net Payout"].sum()
else:
final_share = 0
summary_sheet[f"E{row_num}"] = int(final_share)
summary_sheet[f"E{row_num}"].number_format = '₹ #,##0'
total_sums[f"{service}_final"] = final_share
elif file == "open_records.xlsx":
# Clean and convert Total column
if "Total" in df.columns:
df["Total"] = df["Total"].apply(clean_and_convert_to_float)
total_sum = df["Total"].sum()
else:
total_sum = 0
# For D9, hardcode the value and populate E9 with sum of 'Net Payout'
summary_sheet[f"D{row_num}"] = "10/12/15%"
summary_sheet[f"D{row_num}"].number_format = '@'
if "Net Payout" in df.columns:
df["Net Payout"] = df["Net Payout"].apply(clean_and_convert_to_float)
final_share = df["Net Payout"].sum()
else:
final_share = 0
summary_sheet[f"E{row_num}"] = int(final_share)
summary_sheet[f"E{row_num}"].number_format = '₹ #,##0'
total_sums[f"{service}_final"] = final_share
elif file == "orthopaedic_report_with_tax.xlsx":
# Try to find Net Profit column and sum it
if "Net Profit" in df.columns:
df["Net Profit"] = df["Net Profit"].apply(clean_and_convert_to_float)
total_sum = df["Net Profit"].sum()
else:
total_sum = 0
elif file == "extra_implant_orthopaedics.xlsx":
# Always calculate uhid_count as the count of unique UHID entries
if "UHID" in df.columns:
total_sum = len(df["UHID"].unique())
else:
total_sum = 0
elif file in ["ortho_opd_diagnostics.xlsx", "ortho_opd_pathology.xlsx", "ortho_opd_daycare.xlsx"]:
# For the new report types, sum the Net Amount column
if "Net Amount" in df.columns:
df["Net Amount"] = df["Net Amount"].apply(clean_and_convert_to_float)
total_sum = df["Net Amount"].sum()
else:
total_sum = 0
else:
total_sum = 0
# Store the total sum
total_sums[service] = total_sum
# Format and display the total sum as integer
summary_sheet[f"C{row_num}"] = int(total_sum)
# Check if this row should not have currency symbol
if row_data.get("no_currency", False):
summary_sheet[f"C{row_num}"].number_format = '#,##0'
else:
summary_sheet[f"C{row_num}"].number_format = '₹ #,##0'
# Calculate and display variable share
if variable_share == "hardcoded_d8" or variable_share == "hardcoded_d9":
# D8 and D9 are already handled above
pass
elif isinstance(variable_share, (int, float)) and variable_share > 1:
# This is a hardcoded value (like 30000), not a percentage
summary_sheet[f"D{row_num}"] = int(variable_share)
summary_sheet[f"D{row_num}"].number_format = '#,##0'
# Calculate and display final share as integer
final_share = total_sum * variable_share
summary_sheet[f"E{row_num}"] = int(final_share)
summary_sheet[f"E{row_num}"].number_format = '₹ #,##0'
# Store the final share for total calculation
total_sums[f"{service}_final"] = final_share
elif variable_share is not None:
# This is a percentage (like 0.60)
summary_sheet[f"D{row_num}"] = int(variable_share*100)
summary_sheet[f"D{row_num}"].number_format = '0"%"'
# Calculate and display final share as integer
final_share = total_sum * variable_share
summary_sheet[f"E{row_num}"] = int(final_share)
summary_sheet[f"E{row_num}"].number_format = '₹ #,##0'
# Store the final share for total calculation
total_sums[f"{service}_final"] = final_share
row_num += 1
# Calculate and display total variable
total_final_share = sum([v for k, v in total_sums.items() if k.endswith("_final")])
total_row = row_num
summary_sheet[f"E{row_num}"] = int(total_final_share)
summary_sheet[f"E{row_num}"].number_format = '₹ #,##0'
row_num += 1
row_num += 1
row_num += 1
# Row 17: Professional Fee for Dr. Gurudeo - showing -50,000 in Final Share with minus sign
summary_sheet[f"B{row_num}"] = "Less: Professional Fee for Dr. Gurudeo"
summary_sheet[f"B{row_num}"].font = Font(size=11)
# Don't show value in Total Sum column
summary_sheet[f"E{row_num}"] = -50000 # Negative value to show minus sign
summary_sheet[f"E{row_num}"].number_format = '₹ #,##0'
# Calculate Variable Payable
row_num += 1
variable_payable = total_final_share - 50000 # Only subtract Dr. Gurudeo's fee
summary_sheet[f"E{row_num}"] = int(variable_payable)
summary_sheet[f"E{row_num}"].number_format = '₹ #,##0'
# Calculate TDS
row_num += 1
tds = variable_payable * 0.10
summary_sheet[f"E{row_num}"] = int(tds)
summary_sheet[f"E{row_num}"].number_format = '₹ #,##0'
# Calculate Net Payable
row_num += 1
net_payable = variable_payable - tds
summary_sheet[f"E{row_num}"] = int(net_payable)
summary_sheet[f"E{row_num}"].number_format = '₹ #,##0'
return total_sums
# Function to add individual report sheets
def add_report_sheets(workbook, summary_rows, data_dir):
for row_data in summary_rows:
file = row_data["file"]
service = row_data["service"].replace(" ", "") # Remove leading spaces
if file and os.path.exists(os.path.join(data_dir, file)):
# Read the Excel file
df = pd.read_excel(os.path.join(data_dir, file))
# Create a new sheet with the service name
sheet_name = service[:31] # Excel sheet names are limited to 31 characters
sheet = workbook.create_sheet(sheet_name)
# Write the headers
for col_idx, col_name in enumerate(df.columns, 1):
sheet.cell(row=1, column=col_idx, value=col_name)
sheet.cell(row=1, column=col_idx).font = Font(bold=True)
# Write the data
for row_idx, row in df.iterrows():
for col_idx, value in enumerate(row, 1):
sheet.cell(row=row_idx+2, column=col_idx, value=value)
# Auto-adjust column widths
for col in sheet.columns:
max_length = 0
column = col[0].column_letter
for cell in col:
try:
if len(str(cell.value)) > max_length:
max_length = len(str(cell.value))
except:
pass
adjusted_width = (max_length + 2)
sheet.column_dimensions[column].width = min(adjusted_width, 30)
def create_combined_report(data_dir, output_file, current_month, current_year):
workbook = openpyxl.Workbook()
default_sheet = workbook.active
workbook.remove(default_sheet)
summary_sheet, summary_rows = create_summary_sheet(workbook, data_dir, current_month, current_year)
total_sums = populate_summary_data(summary_sheet, summary_rows, data_dir, current_month, current_year)
add_report_sheets(workbook, summary_rows, data_dir)
workbook.save(output_file)
return output_file, total_sums
if __name__ == "__main__":
data_dir = "."
output_file = f"Ortho_Variable_Report-{current_month}-{current_year}.xlsx"
current_month = "June"
current_year = "25"
report_file, totals = create_combined_report(data_dir, output_file, current_month, current_year)
print(f"Combined report created: {report_file}")
print(f"Total sums: {totals}")
# FINAL WRAPPER FUNCTION
import tempfile
import shutil
import os
import pandas as pd
from datetime import datetime
def generate_ortho_revenue(
hospital_revenue_report_path, # 1. print_hospital_revenue_report.php.xls
inpatient_bill_register_path, # 2. print_inpatient_bill_register_report.xls
doctor_visit_with_package_path, # 3. doctor_visit_report_with_package.xls
doctor_visit_without_package_path, # 4. doctor_visit_report_without_package.xls
doctor_ot_with_package_path, # 5. doctor_ot_with_package.xls
doctor_ot_without_package_path, # 6. doctor_ot_without_package.xls
grn_details_report_path, # 7. print_grn_details_report.xls
item_sale_report_path, # 8. print_item_sale_report.xls
current_month,
current_year
):
"""
End-to-end processing for Orthopaedics Department Revenue Report
Args:
All 8 file paths as strings
current_month: Month name (e.g., "May")
current_year: Year as string (e.g., "2025")
Returns:
Path to final summary report or None if error
"""
try:
# Create temporary workspace
with tempfile.TemporaryDirectory() as tmpdir:
print(f"Processing Orthopaedics Revenue for {current_month} {current_year}")
# Step 1: Convert first 7 HTML files to Excel using standard converter
print("\n[Step 1/10] Converting HTML files to Excel...")
file_list = [
doctor_ot_with_package_path,
doctor_ot_without_package_path,
doctor_visit_with_package_path,
doctor_visit_without_package_path,
hospital_revenue_report_path,
inpatient_bill_register_path,
grn_details_report_path
]
# Process the first 7 files
results = []
for i, input_file in enumerate(file_list):
print(f"\n[File {i+1}/{len(file_list)}] Processing: {os.path.basename(input_file)}")
base_name = os.path.splitext(os.path.basename(input_file))[0]
output_file = os.path.join(tmpdir, f"processed_{base_name}.xlsx")
try:
convert_html_to_excel(input_file, output_file)
results.append((input_file, output_file, "Success"))
except Exception as e:
print(f"× ERROR processing {input_file}: {str(e)}")
results.append((input_file, None, f"Error: {str(e)}"))
# Map converted files for easy access (DYNAMIC VERSION)
file_params = [
('hospital_revenue', hospital_revenue_report_path),
('inpatient_bill', inpatient_bill_register_path),
('doctor_visit_with_package', doctor_visit_with_package_path),
('doctor_visit_without_package', doctor_visit_without_package_path),
('doctor_ot_with_package', doctor_ot_with_package_path),
('doctor_ot_without_package', doctor_ot_without_package_path),
('grn_details', grn_details_report_path)
]
converted_files = {
logical_name: os.path.join(tmpdir, f"processed_{os.path.splitext(os.path.basename(file_path))[0]}.xlsx")
for logical_name, file_path in file_params
}
# Step 2: Process OPD Consultations
print("\n[Step 2/10] Filtering OPD consultations...")
opd_consultations_path = os.path.join(tmpdir, "processed_opd_consultations.xlsx")
results = filter_patient_records(
converted_files['hospital_revenue'],
'Orthopaedics'
)
results.to_excel(opd_consultations_path, index=False)
# Step 3: Combine doctor visit reports
print("\n[Step 3/10] Combining doctor visit reports...")
df_visit_pkg = pd.read_excel(converted_files['doctor_visit_with_package'])
df_visit_no_pkg = pd.read_excel(converted_files['doctor_visit_without_package'])
df_visit_pkg['Type'] = 'Package'
df_visit_no_pkg['Type'] = 'Open'
df_visit_combined = pd.concat([df_visit_pkg, df_visit_no_pkg], axis=0, ignore_index=True)
visit_combined_path = os.path.join(tmpdir, "final_processed_doctor_visit_report.xlsx")
df_visit_combined.to_excel(visit_combined_path, index=False)
# Step 4: Tag consultations as Self/Cross
print("\n[Step 4/10] Tagging consultations...")
df_visits = pd.read_excel(visit_combined_path)
df_admissions = pd.read_excel(converted_files['inpatient_bill'])
# Process for all target doctors
doctors = [
'Dr. Nishikant Kumar',
'Dr. GURUDEO KUMAR',
'Dr Ramit Gunjan',
'Dr SAURABH CHAUDHARY'
]
df_visits['Consultation Type'] = pd.NA
for doctor_name in doctors:
norm_input = normalize_doctor_name(doctor_name)
admissions = (
df_admissions[df_admissions['Admiting Doctor']
.map(normalize_doctor_name) == norm_input]
['Admission No.']
.unique()
)
mask_doc = df_visits['Doctor Name'].map(normalize_doctor_name) == norm_input
mask_adm = df_visits['Admission No.'].isin(admissions)
df_visits.loc[mask_doc & mask_adm, 'Consultation Type'] = 'Self'
df_visits.loc[mask_doc & ~mask_adm, 'Consultation Type'] = 'Cross'
tagged_consultations_path = os.path.join(tmpdir, "precision_tagged_all_consultations.xlsx")
df_visits.to_excel(tagged_consultations_path, index=False)
# Step 5: Extract Self/Open and Cross records
print("\n[Step 5/10] Extracting Self/Open and Cross consultations...")
self_open_path = os.path.join(tmpdir, "self_open_for_doctors.xlsx")
filtered_self = get_self_open_records(tagged_consultations_path, doctors)
filtered_self.to_excel(self_open_path, index=False)
cross_path = os.path.join(tmpdir, "cross_for_doctors.xlsx")
filtered_cross = get_cross_records(tagged_consultations_path, doctors)
filtered_cross.to_excel(cross_path, index=False)
# Step 6: Combine OT reports and calculate surgeon payouts
print("\n[Step 6/10] Processing surgeon payouts...")
df_ot_pkg = pd.read_excel(converted_files['doctor_ot_with_package'])
df_ot_no_pkg = pd.read_excel(converted_files['doctor_ot_without_package'])
df_ot_pkg['Type'] = 'Package'
df_ot_no_pkg['Type'] = 'Open'
df_ot_combined = pd.concat([df_ot_pkg, df_ot_no_pkg], axis=0, ignore_index=True)
ot_combined_path = os.path.join(tmpdir, "final_processed_doctor_ot_report.xlsx")
df_ot_combined.to_excel(ot_combined_path, index=False)
# Process surgeon payouts (this creates package_records.xlsx and open_records.xlsx)
package_path = os.path.join(tmpdir, "package_records.xlsx")
open_path = os.path.join(tmpdir, "open_records.xlsx")
# Create temporary process_surgeon_payouts that saves to tmpdir
process_surgeon_payouts_to_tmpdir(
ot_combined_path,
converted_files['inpatient_bill'],
doctors,
package_path,
open_path
)
# Step 7: Process item sale report with special separator handling
print("\n[Step 7/10] Processing item sale report with separator...")
# First convert with separator handling
processed_item_sale_path = os.path.join(tmpdir, "processed_print_item_sale_report.xlsx")
base_name = os.path.splitext(os.path.basename(item_sale_report_path))[0]
convert_html_to_excel_with_separator(item_sale_report_path, processed_item_sale_path)
# Process with separator to adjust values
modified_report_path = os.path.join(tmpdir, "final_modified_report.xlsx")
process_excel_with_separator(processed_item_sale_path, modified_report_path)
# Apply tax calculations and filters
ortho_tax_report_path = os.path.join(tmpdir, "orthopaedic_report_with_tax.xlsx")
process_reports(
modified_report_path,
converted_files['grn_details'],
ortho_tax_report_path
)
# Step 8: Extract extra implant charges
print("\n[Step 8/10] Extracting extra implant charges...")
extra_implant_path = os.path.join(tmpdir, "extra_implant_orthopaedics.xlsx")
filtered_implant, _ = filter_extra_implant_charges(converted_files['hospital_revenue'])
filtered_implant.to_excel(extra_implant_path, index=False)
# Step 9: Generate service reports
print("\n[Step 9/10] Generating service reports...")
generate_ortho_service_report(
converted_files['hospital_revenue'],
'Diagnostic',
os.path.join(tmpdir, 'ortho_opd_diagnostics.xlsx')
)
generate_ortho_service_report(
converted_files['hospital_revenue'],
'Pathology',
os.path.join(tmpdir, 'ortho_opd_pathology.xlsx')
)
generate_ortho_service_report(
converted_files['hospital_revenue'],
'Day Care Procedure',
os.path.join(tmpdir, 'ortho_opd_daycare.xlsx')
)
# Step 10: Create final summary report
print("\n[Step 10/10] Creating final summary report...")
final_report_name = f"Ortho_Variable_Report-{current_month}-{current_year}.xlsx"
final_report_path = os.path.join(tmpdir, final_report_name)
# Create the combined report
create_combined_report(tmpdir, final_report_path, current_month, current_year)
# Copy final output to permanent location
permanent_output = os.path.join(os.getcwd(), final_report_name)
shutil.copy(final_report_path, permanent_output)
print(f"✓ Processing complete! Final report saved to: {permanent_output}")
return permanent_output
except Exception as e:
print(f"❌ Orthopaedics processing error: {str(e)}")
import traceback
traceback.print_exc()
return None
def process_surgeon_payouts_to_tmpdir(ot_report_path, bill_register_path,
doctor_list, package_out_path, open_out_path):
"""Modified version of process_surgeon_payouts that saves to specific paths"""
import warnings
warnings.filterwarnings('ignore',
category=pd.errors.SettingWithCopyWarning)
# Run the original process_surgeon_payouts
# But we need to capture the output files and move them
# Temporarily change to a work directory to avoid conflicts
original_dir = os.getcwd()
work_dir = os.path.dirname(package_out_path)
os.chdir(work_dir)
try:
# Call the original function
process_surgeon_payouts(ot_report_path, bill_register_path, doctor_list)
# The files are created in the current directory, rename them to the desired paths
if os.path.exists("package_records.xlsx"):
os.rename("package_records.xlsx", os.path.basename(package_out_path))
if os.path.exists("open_records.xlsx"):
os.rename("open_records.xlsx", os.path.basename(open_out_path))
finally:
# Change back to original directory
os.chdir(original_dir)
# Example usage:
if __name__ == "__main__":
input_files = [
'/content/Rev Report.xls',
'/content/IP Bill register.xls',
'/content/Doctor visit with package.xls',
'/content/Doctor visit without package.xls',
'/content/Doctor OT with package.xls',
'/content/Doctor OT without package.xls',
'/content/GRN.xls',
'/content/Item Sale Report.xls'
]
result = generate_ortho_revenue(
*input_files,
current_month="June",
current_year="25"
)
if result:
print(f"Success! Final report: {result}")
else:
print("Processing failed.")
|