Spaces:
Sleeping
Sleeping
Download parser.py from Vignesh5656/transformation-api: direct link, hf CLI and curl.
- Browser
- Download file 17.9 kB
-
https://huggingface.co/spaces/Vignesh5656/transformation-api/resolve/main/parser.py
- Command line
-
hf download hf://spaces/Vignesh5656/transformation-api/parser.py
-
curl -L -o parser.py https://huggingface.co/spaces/Vignesh5656/transformation-api/resolve/main/parser.py
17.9 kB
| #!/usr/bin/env python3 | |
| """ | |
| Excel Parser Script for Benefit Agent Analysis Report | |
| This script reads data from data.json and generates an Excel report (OUTPUT.xlsx) | |
| in the format specified in expected-output.txt. | |
| Business Rules: | |
| - New records: At least 80% of total records | |
| - Update records: Total records - new records - failure records | |
| - Failure records: Less than total records - new records | |
| """ | |
| import json | |
| import os | |
| import random | |
| import argparse | |
| from datetime import datetime | |
| from openpyxl import Workbook | |
| from openpyxl.styles import Font, PatternFill, Alignment, Border, Side | |
| from openpyxl.utils import get_column_letter | |
| from typing import Dict, List, Tuple, Any | |
| class BenefitAgentExcelReportGenerator: | |
| def __init__(self, data_file: str = "static/data.json", output_file: str = "static/OUTPUT.xlsx"): | |
| self.data_file = data_file | |
| self.output_file = output_file | |
| self.data = None | |
| self.workbook = None | |
| self.worksheet = None | |
| self.current_row = 1 | |
| # Define color scheme (similar to PDF version) | |
| self.primary_blue = "1E3A8A" # Dark navy blue | |
| self.secondary_blue = "3B82F6" # Medium blue | |
| self.light_blue = "EBF8FF" # Very light blue | |
| self.accent_blue = "93C5FD" # Light accent blue | |
| def load_data(self) -> bool: | |
| """Load data from JSON file""" | |
| try: | |
| # Get the absolute path | |
| script_dir = os.path.dirname(os.path.abspath(__file__)) | |
| file_path = os.path.join(script_dir, self.data_file) | |
| with open(file_path, 'r') as f: | |
| self.data = json.load(f) | |
| print(f"β Successfully loaded data from {file_path}") | |
| print(f" Request ID: {self.data.get('requestId')}") | |
| print(f" Total records: {len(self.data.get('values', []))}") | |
| return True | |
| except FileNotFoundError: | |
| print(f"β Error: File {file_path} not found") | |
| return False | |
| except json.JSONDecodeError: | |
| print(f"β Error: Invalid JSON format in {file_path}") | |
| return False | |
| except Exception as e: | |
| print(f"β Error loading data: {e}") | |
| return False | |
| def get_user_input_for_statistics(self) -> Dict[str, int]: | |
| """ | |
| Prompt user for record statistics | |
| Returns: | |
| Dictionary with counts for total, new, update, and failure records | |
| """ | |
| if not self.data or 'values' not in self.data: | |
| return {"total": 0, "new": 0, "update": 0, "failure": 0} | |
| total_records = len(self.data['values']) | |
| print(f"\nπ Record Statistics Input") | |
| print(f"{'='*40}") | |
| print(f"Total number of records available: {total_records}") | |
| print() | |
| while True: | |
| try: | |
| print("Please enter the record counts:") | |
| new_records = int(input(f"π Number of new records (recommended: {int(total_records * 0.8)}): ").strip()) | |
| if new_records < 0 or new_records > total_records: | |
| print(f"β New records must be between 0 and {total_records}") | |
| continue | |
| failure_records = int(input(f"β Number of failure records (max: {total_records - new_records}): ").strip()) | |
| if failure_records < 0 or failure_records > total_records - new_records: | |
| print(f"β Failure records must be between 0 and {total_records - new_records}") | |
| continue | |
| update_records = total_records - new_records - failure_records | |
| print(f"\nπ Calculated Statistics:") | |
| print(f" β’ Total records: {total_records}") | |
| print(f" β’ New records: {new_records}") | |
| print(f" β’ Update records: {update_records}") | |
| print(f" β’ Failure records: {failure_records}") | |
| confirm = input("\nβ Confirm these statistics? (y/n): ").strip().lower() | |
| if confirm in ['y', 'yes']: | |
| break | |
| except ValueError: | |
| print("β Please enter valid numbers") | |
| except KeyboardInterrupt: | |
| print("\n\nπ Operation cancelled by user") | |
| return {"total": 0, "new": 0, "update": 0, "failure": 0} | |
| stats = { | |
| "total": total_records, | |
| "new": new_records, | |
| "update": update_records, | |
| "failure": failure_records | |
| } | |
| return stats | |
| def get_automatic_statistics(self) -> Dict[str, int]: | |
| """ | |
| Generate automatic statistics following business rules | |
| Returns: | |
| Dictionary with counts for total, new, update, and failure records | |
| """ | |
| if not self.data or 'values' not in self.data: | |
| return {"total": 0, "new": 0, "update": 0, "failure": 0} | |
| total_records = len(self.data['values']) | |
| # Business rules | |
| new_records = max(1, int(total_records * 0.8)) # At least 80% are new | |
| failure_records = max(1, min(3, total_records - new_records)) # Small number of failures | |
| update_records = total_records - new_records - failure_records | |
| stats = { | |
| "total": total_records, | |
| "new": new_records, | |
| "update": update_records, | |
| "failure": failure_records | |
| } | |
| print(f"π€ Automatic Statistics Generated:") | |
| print(f" β’ Total records: {total_records}") | |
| print(f" β’ New records: {new_records}") | |
| print(f" β’ Update records: {update_records}") | |
| print(f" β’ Failure records: {failure_records}") | |
| return stats | |
| def split_records(self, stats: Dict[str, int]) -> Tuple[List[List], List[List]]: | |
| """ | |
| Split records into successful and failure records | |
| Args: | |
| stats: Record statistics dictionary | |
| Returns: | |
| Tuple of (successful_records, failure_records) | |
| """ | |
| if not self.data or 'values' not in self.data: | |
| return [], [] | |
| all_records = self.data['values'].copy() | |
| random.shuffle(all_records) # Randomize which records are failures | |
| # Split records based on calculated statistics | |
| failure_count = stats['failure'] | |
| if failure_count > 0: | |
| failure_records = all_records[-failure_count:] | |
| successful_records = all_records[:-failure_count] | |
| else: | |
| failure_records = [] | |
| successful_records = all_records | |
| return successful_records, failure_records | |
| def setup_workbook(self): | |
| """Initialize the Excel workbook and worksheet""" | |
| self.workbook = Workbook() | |
| self.worksheet = self.workbook.active | |
| self.worksheet.title = "Benefit Agent Analysis Report" | |
| self.current_row = 1 | |
| def add_title(self): | |
| """Add the main title to the Excel sheet""" | |
| title_cell = self.worksheet.cell(row=self.current_row, column=1) | |
| title_cell.value = "Benefit Agent Analysis Report" | |
| title_cell.font = Font(name='Arial', size=18, bold=True, color=self.primary_blue) | |
| title_cell.alignment = Alignment(horizontal='center') | |
| # Merge cells for title | |
| self.worksheet.merge_cells(f'A{self.current_row}:F{self.current_row}') | |
| self.current_row += 2 | |
| def add_summary_section(self, stats: Dict[str, int]): | |
| """Add the summary section to the Excel sheet""" | |
| current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") | |
| # Summary title | |
| summary_title_cell = self.worksheet.cell(row=self.current_row, column=1) | |
| summary_title_cell.value = "Summary" | |
| summary_title_cell.font = Font(name='Arial', size=14, bold=True, color=self.primary_blue) | |
| self.current_row += 1 | |
| # Summary items | |
| summary_items = [ | |
| f"Total Number of records: {stats['total']}", | |
| f"Number of new records: {stats['new']}", | |
| f"Number of update records: {stats['update']}", | |
| f"Number of Records failing Validation: {stats['failure']}", | |
| "Generated By: Benefit Agent", | |
| "Requested By: John Doe", | |
| f"Requested Date: {current_time}" | |
| ] | |
| for item in summary_items: | |
| cell = self.worksheet.cell(row=self.current_row, column=1) | |
| cell.value = item | |
| cell.font = Font(name='Arial', size=10) | |
| self.current_row += 1 | |
| self.current_row += 1 # Add space after summary | |
| def add_table(self, data: List[List], title: str): | |
| """ | |
| Add a table with proper formatting to the Excel sheet | |
| Args: | |
| data: List of rows (including header) | |
| title: Title for the table | |
| """ | |
| if not data: | |
| # Add "No records" message | |
| cell = self.worksheet.cell(row=self.current_row, column=1) | |
| cell.value = f"{title}: No records to display" | |
| cell.font = Font(name='Arial', size=11, italic=True) | |
| self.current_row += 2 | |
| return | |
| # Add table title | |
| title_cell = self.worksheet.cell(row=self.current_row, column=1) | |
| title_cell.value = title | |
| title_cell.font = Font(name='Arial', size=12, bold=True, color=self.secondary_blue) | |
| self.current_row += 1 | |
| start_row = self.current_row | |
| # Add table data | |
| for row_idx, row_data in enumerate(data): | |
| for col_idx, cell_value in enumerate(row_data): | |
| cell = self.worksheet.cell(row=self.current_row, column=col_idx + 1) | |
| cell.value = cell_value | |
| cell.alignment = Alignment(horizontal='center', vertical='center') | |
| # Header row styling | |
| if row_idx == 0: | |
| cell.font = Font(name='Arial', size=10, bold=True, color='FFFFFF') | |
| cell.fill = PatternFill(start_color=self.primary_blue, end_color=self.primary_blue, fill_type='solid') | |
| else: | |
| cell.font = Font(name='Arial', size=9) | |
| # Alternate row coloring | |
| if row_idx % 2 == 0: | |
| cell.fill = PatternFill(start_color=self.light_blue, end_color=self.light_blue, fill_type='solid') | |
| # Add borders | |
| thin_border = Border( | |
| left=Side(style='thin', color=self.secondary_blue), | |
| right=Side(style='thin', color=self.secondary_blue), | |
| top=Side(style='thin', color=self.secondary_blue), | |
| bottom=Side(style='thin', color=self.secondary_blue) | |
| ) | |
| cell.border = thin_border | |
| self.current_row += 1 | |
| # Auto-adjust column widths | |
| end_row = self.current_row - 1 | |
| num_cols = len(data[0]) if data else 0 | |
| for col_idx in range(1, num_cols + 1): | |
| column_letter = get_column_letter(col_idx) | |
| max_width = 0 | |
| for row_idx in range(start_row, end_row + 1): | |
| cell_value = str(self.worksheet.cell(row=row_idx, column=col_idx).value or "") | |
| max_width = max(max_width, len(cell_value)) | |
| # Set reasonable width limits | |
| adjusted_width = min(max(max_width + 2, 10), 30) | |
| self.worksheet.column_dimensions[column_letter].width = adjusted_width | |
| self.current_row += 1 # Add space after table | |
| def prepare_successful_records_table(self, successful_records: List[List]) -> List[List]: | |
| """Prepare successful records table data dynamically based on data.json columns""" | |
| if not successful_records: | |
| return [] | |
| # Get columns from data.json dynamically | |
| columns = self.data.get('columns', []) | |
| # Create dynamic table header with S.NO. and REQUEST ID as first columns, then data columns | |
| table_header = ["S.NO.", "REQUEST ID"] + [col.upper() for col in columns] | |
| table_data = [table_header] | |
| # Add data rows dynamically | |
| for i, record in enumerate(successful_records, 1): | |
| row = [str(i), self.data.get('requestId', '')] + [str(value) for value in record] | |
| table_data.append(row) | |
| return table_data | |
| def prepare_failure_records_table(self, failure_records: List[List]) -> List[List]: | |
| """Prepare failure records table data dynamically based on data.json columns""" | |
| if not failure_records: | |
| return [] | |
| # Get columns from data.json dynamically | |
| columns = self.data.get('columns', []) | |
| # Create dynamic table header - same structure as successful records | |
| table_header = ["S.NO.", "REQUEST ID"] + [col.upper() for col in columns] | |
| table_data = [table_header] | |
| # Add data rows dynamically | |
| for i, record in enumerate(failure_records, 1): | |
| row = [str(i), self.data.get('requestId', '')] + [str(value) for value in record] | |
| table_data.append(row) | |
| return table_data | |
| def generate_excel(self, interactive: bool = True) -> bool: | |
| """Generate the Excel report following the expected output format""" | |
| try: | |
| # Get statistics | |
| if interactive: | |
| stats = self.get_user_input_for_statistics() | |
| else: | |
| stats = self.get_automatic_statistics() | |
| if stats['total'] == 0: | |
| print("β No data to process") | |
| return False | |
| # Split records | |
| successful_records, failure_records = self.split_records(stats) | |
| print(f"\nπ Processing Records:") | |
| print(f" β’ Successful records: {len(successful_records)}") | |
| print(f" β’ Failure records: {len(failure_records)}") | |
| # Setup workbook | |
| self.setup_workbook() | |
| # Add title | |
| self.add_title() | |
| # Add summary section | |
| self.add_summary_section(stats) | |
| # Add successful records table | |
| successful_table_data = self.prepare_successful_records_table(successful_records) | |
| self.add_table(successful_table_data, "Generated Records") | |
| # Add failure records table | |
| failure_table_data = self.prepare_failure_records_table(failure_records) | |
| self.add_table(failure_table_data, "Failure Records") | |
| # Save the workbook | |
| script_dir = os.path.dirname(os.path.abspath(__file__)) | |
| output_path = os.path.join(script_dir, self.output_file) | |
| self.workbook.save(output_path) | |
| print(f"β Excel report saved successfully: {output_path}") | |
| return True | |
| except Exception as e: | |
| print(f"β Error generating Excel report: {e}") | |
| return False | |
| def run(self, interactive: bool = True) -> bool: | |
| """Run the complete parsing and Excel generation process""" | |
| print("π Starting Professional Benefit Agent Excel Report Generation") | |
| print("=" * 60) | |
| # Load data | |
| if not self.load_data(): | |
| return False | |
| # Generate Excel | |
| if not self.generate_excel(interactive=interactive): | |
| return False | |
| print("β Professional Excel report generation completed successfully!") | |
| return True | |
| def main(): | |
| """Main function""" | |
| parser = argparse.ArgumentParser(description="Generate Professional Benefit Agent Analysis Excel Report") | |
| parser.add_argument("--data", default="static/data.json", help="Path to input data JSON file") | |
| parser.add_argument("--output", default="static/OUTPUT.xlsx", help="Path for output Excel file") | |
| parser.add_argument("--auto", action="store_true", help="Run in automatic mode (no user input)") | |
| parser.add_argument("--verbose", "-v", action="store_true", help="Verbose output") | |
| args = parser.parse_args() | |
| # Create report generator | |
| generator = BenefitAgentExcelReportGenerator(args.data, args.output) | |
| # Determine if interactive mode | |
| interactive_mode = not args.auto | |
| print(f"π Mode: {'Interactive' if interactive_mode else 'Automatic'}") | |
| if interactive_mode: | |
| print("π‘ You will be prompted to enter record statistics") | |
| else: | |
| print("π€ Using automatic calculation for record statistics") | |
| print() | |
| # Run the generation process | |
| success = generator.run(interactive=interactive_mode) | |
| if success: | |
| print("\nπ Professional Excel report generated successfully!") | |
| print(f"π Output file: {args.output}") | |
| print("π The report includes:") | |
| print(" β’ Professional executive summary") | |
| print(" β’ Properly formatted and aligned tables") | |
| print(" β’ Enhanced styling and colors") | |
| print(" β’ Comprehensive record statistics") | |
| print(" β’ Auto-sized columns for readability") | |
| else: | |
| print("\nβ Report generation failed!") | |
| return 1 | |
| return 0 | |
| if __name__ == "__main__": | |
| exit(main()) |