import gradio as gr import pandas as pd import numpy as np from numpy.random import default_rng import io # For BytesIO to handle file in memory # 1. Data Generation Function (customizable via UI filters) def generate_custom_model_points( mp_count_val, seed_val, age_min_val, age_max_val, sa_min_val, sa_max_val, policy_terms_selection_val, include_sex_val, policy_count_fixed_val ): """ Generates seriatim model points based on user-defined parameters. """ rng = default_rng(int(seed_val)) mp_count_val = int(mp_count_val) age_min_val = int(age_min_val) age_max_val = int(age_max_val) sa_min_val = float(sa_min_val) sa_max_val = float(sa_max_val) # Policy ID policy_id_col = np.arange(1, mp_count_val + 1) # Issue Age age_at_entry = rng.integers(low=age_min_val, high=age_max_val + 1, size=mp_count_val) # Sex if include_sex_val: sex_options = ["M", "F"] sex_col = np.fromiter(map(lambda i: sex_options[i], rng.integers(low=0, high=len(sex_options), size=mp_count_val)), np.dtype('= int(age_mx): gr.Warning("Minimum Age must be less than Maximum Age.") return df_state.value, df_state.value # Keep current table and state if float(sa_m) >= float(sa_mx): gr.Warning("Minimum Sum Assured must be less than Maximum Sum Assured.") return df_state.value, df_state.value if not p_terms: gr.Warning("No Policy Terms selected. Using defaults: [10, 15, 20].") # Generation function will handle default if p_terms is empty list gr.Info("Generating model points... Please wait.") df = generate_custom_model_points( mp_c, s, age_m, age_mx, sa_m, sa_mx, p_terms, incl_sex, pc_fixed ) gr.Info(f"{len(df)} model points generated successfully!") return df, df def handle_download_button_click(current_df_to_download): if current_df_to_download is None or current_df_to_download.empty: gr.Warning("No data available to download. Generate model points first.") empty_excel_output = io.BytesIO() pd.DataFrame().to_excel(empty_excel_output, index=False) empty_excel_output.seek(0) return empty_excel_output excel_output = io.BytesIO() current_df_to_download.to_excel(excel_output, sheet_name='ModelPoints', engine='xlsxwriter', index=False) excel_output.seek(0) return excel_output # Wire up UI components to functions inputs_list = [ mp_count_input, seed_input, age_min_input, age_max_input, sum_assured_min_input, sum_assured_max_input, policy_terms_input, include_sex_input, policy_count_fixed_input ] generate_btn.click( fn=handle_generate_button_click, inputs=inputs_list, outputs=[model_points_display, df_state] ) download_excel_btn.click( fn=handle_download_button_click, inputs=[df_state], outputs=[download_excel_btn] ) if __name__ == "__main__": demo.launch()