Spaces:
Sleeping

rr_payout_test / variable /ortho_variable.py
mhpl's picture
Upload 5 files
34a733e verified
Raw History Blame Contribute Delete
66.1 kB
# -*- 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.")
# -*- 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):,}")