File size: 44,164 Bytes
48f9ec0 7e3da34 48f9ec0 208c4cb 48f9ec0 7e3da34 48f9ec0 709c686 48f9ec0 d6d4fca 48f9ec0 208c4cb 48f9ec0 208c4cb 48f9ec0 208c4cb 48f9ec0 208c4cb 48f9ec0 208c4cb 48f9ec0 208c4cb 48f9ec0 208c4cb 48f9ec0 208c4cb 48f9ec0 208c4cb 48f9ec0 208c4cb 48f9ec0 208c4cb 48f9ec0 208c4cb 48f9ec0 208c4cb 48f9ec0 208c4cb 48f9ec0 208c4cb 48f9ec0 208c4cb 48f9ec0 208c4cb 48f9ec0 208c4cb 48f9ec0 208c4cb 48f9ec0 |
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 |
# # intervention_analysis_app.py
# import streamlit as st
# import pandas as pd
# # from transformers import pipeline
# from huggingface_hub import InferenceClient
# import os
# from pathlib import Path
# from dotenv import load_dotenv
# load_dotenv()
# # Set the Hugging Face API key
# # Retrieve Hugging Face API key from environment variables
# hf_api_key = os.getenv('HF_API_KEY')
# if not hf_api_key:
# raise ValueError("HF_API_KEY not set in environment variables")
# # Create the Hugging Face inference client
# client = InferenceClient(api_key=hf_api_key)
# # Constants
# INTERVENTION_COLUMN = 'Did the intervention happen today?'
# ENGAGED_STR = 'Engaged (Respect, Responsibility, Effort)'
# PARTIALLY_ENGAGED_STR = 'Partially Engaged (about 50%)'
# NOT_ENGAGED_STR = 'Not Engaged (less than 50%)'
# def main():
# st.title("Intervention Program Analysis")
# # File uploader
# uploaded_file = st.file_uploader("Upload your Excel file", type=["xlsx"])
# if uploaded_file is not None:
# try:
# # Read the Excel file into a DataFrame
# df = pd.read_excel(uploaded_file)
# st.subheader("Uploaded Data")
# st.write(df)
# # Ensure expected column is available
# if INTERVENTION_COLUMN not in df.columns:
# st.error(f"Expected column '{INTERVENTION_COLUMN}' not found.")
# return
# # Clean up column names
# df.columns = df.columns.str.strip()
# # Compute Intervention Session Statistics
# intervention_stats = compute_intervention_statistics(df)
# st.subheader("Intervention Session Statistics")
# st.write(intervention_stats)
# # Compute Student Metrics
# student_metrics_df = compute_student_metrics(df)
# st.subheader("Student Metrics")
# st.write(student_metrics_df)
# # Prepare input for the language model
# llm_input = prepare_llm_input(student_metrics_df)
# # Generate Notes and Recommendations using Hugging Face LLM
# recommendations = prompt_response_from_hf_llm(llm_input)
# st.subheader("AI Analysis")
# st.markdown(recommendations)
# except Exception as e:
# st.error(f"Error reading the file: {str(e)}")
# def compute_intervention_statistics(df):
# # Total Number of Days Available
# total_days = len(df)
# # Intervention Sessions Held
# sessions_held = df[INTERVENTION_COLUMN].str.strip().str.lower().eq('yes').sum()
# # Intervention Sessions Not Held
# sessions_not_held = df[INTERVENTION_COLUMN].str.strip().str.lower().eq('no').sum()
# # Intervention Frequency (%)
# intervention_frequency = (sessions_held / total_days) * 100 if total_days > 0 else 0
# intervention_frequency = round(intervention_frequency, 2)
# # Create a DataFrame to display the statistics
# stats = {
# 'Total Number of Days Available': [total_days],
# 'Intervention Sessions Held': [sessions_held],
# 'Intervention Sessions Not Held': [sessions_not_held],
# 'Intervention Frequency (%)': [intervention_frequency]
# }
# stats_df = pd.DataFrame(stats)
# return stats_df
# def compute_student_metrics(df):
# # Filter DataFrame for sessions where intervention happened
# intervention_df = df[df[INTERVENTION_COLUMN].str.strip().str.lower() == 'yes']
# intervention_sessions_held = len(intervention_df)
# # Get list of student columns
# student_columns = [col for col in df.columns if col.startswith('Student Attendance')]
# student_metrics = {}
# for col in student_columns:
# student_name = col.replace('Student Attendance [', '').replace(']', '').strip()
# # Get the attendance data for the student
# student_data = intervention_df[[col]].copy()
# # Treat blank entries as 'Absent'
# student_data[col] = student_data[col].fillna('Absent')
# # Assign attendance values
# attendance_values = student_data[col].apply(lambda x: 1 if x in [
# ENGAGED_STR,
# PARTIALLY_ENGAGED_STR,
# NOT_ENGAGED_STR
# ] else 0)
# # Number of Sessions Attended
# sessions_attended = attendance_values.sum()
# # Attendance (%)
# attendance_pct = (sessions_attended / intervention_sessions_held) * 100 if intervention_sessions_held > 0 else 0
# attendance_pct = round(attendance_pct, 2)
# # For engagement calculation, include only sessions where attendance is not 'Absent'
# valid_engagement_indices = attendance_values[attendance_values == 1].index
# engagement_data = student_data.loc[valid_engagement_indices, col]
# # Assign engagement values
# engagement_values = engagement_data.apply(lambda x: 1 if x == ENGAGED_STR
# else 0.5 if x == PARTIALLY_ENGAGED_STR else 0)
# # Sum of Engagement Values
# sum_engagement_values = engagement_values.sum()
# # Number of Sessions Attended for engagement (should be same as sessions_attended)
# number_sessions_attended = len(valid_engagement_indices)
# # Engagement (%)
# engagement_pct = (sum_engagement_values / number_sessions_attended) * 100 if number_sessions_attended > 0 else 0
# engagement_pct = round(engagement_pct, 2)
# # Store metrics
# student_metrics[student_name] = {
# 'Attendance (%)': attendance_pct,
# 'Engagement (%)': engagement_pct
# }
# # Create a DataFrame from student_metrics
# student_metrics_df = pd.DataFrame.from_dict(student_metrics, orient='index').reset_index()
# student_metrics_df.rename(columns={'index': 'Student'}, inplace=True)
# return student_metrics_df
# def prepare_llm_input(student_metrics_df):
# # Convert the student metrics DataFrame to a string
# metrics_str = student_metrics_df.to_string(index=False)
# llm_input = f"""
# Based on the following student metrics:
# {metrics_str}
# Provide:
# 1. Notes and Key Takeaways: Summarize the data, highlight students with the lowest and highest attendance and engagement percentages, identify students who may need adjustments to their intervention due to low attendance or engagement, and highlight students who are showing strong performance.
# 2. Recommendations and Next Steps: Provide interpretations based on the analysis and suggest possible next steps or strategies to improve student outcomes.
# """
# return llm_input
# def prompt_response_from_hf_llm(llm_input):
# # Generate the refined prompt using Hugging Face API
# response = client.chat.completions.create(
# # model="mistralai/Mistral-7B-Instruct-v0.3",
# model="meta-llama/Llama-3.1-70B-Instruct",
# messages=[
# {"role": "user", "content": llm_input}
# ],
# stream=True,
# temperature=0.5,
# max_tokens=1024,
# top_p=0.7
# )
# # Combine messages if response is streamed
# response_content = ""
# for message in response:
# response_content += message.choices[0].delta.content
# return response_content.strip()
# if __name__ == '__main__':
# main()
# CHARTS
# # intervention_analysis_app.py
# import streamlit as st
# import pandas as pd
# import matplotlib.pyplot as plt
# # from transformers import pipeline
# from huggingface_hub import InferenceClient
# import os
# from pathlib import Path
# from dotenv import load_dotenv
# load_dotenv()
# # Set the Hugging Face API key
# # Retrieve Hugging Face API key from environment variables
# hf_api_key = os.getenv('HF_API_KEY')
# if not hf_api_key:
# raise ValueError("HF_API_KEY not set in environment variables")
# # Create the Hugging Face inference client
# client = InferenceClient(api_key=hf_api_key)
# # Constants
# INTERVENTION_COLUMN = 'Did the intervention happen today?'
# ENGAGED_STR = 'Engaged (Respect, Responsibility, Effort)'
# PARTIALLY_ENGAGED_STR = 'Partially Engaged (about 50%)'
# NOT_ENGAGED_STR = 'Not Engaged (less than 50%)'
# def main():
# st.title("Intervention Program Analysis")
# # File uploader
# uploaded_file = st.file_uploader("Upload your Excel file", type=["xlsx"])
# if uploaded_file is not None:
# try:
# # Read the Excel file into a DataFrame
# df = pd.read_excel(uploaded_file)
# st.subheader("Uploaded Data")
# # st.write(df.head(4)) # Display only the first four rows
# st.write(df) # Display all
# # Ensure expected column is available
# if INTERVENTION_COLUMN not in df.columns:
# st.error(f"Expected column '{INTERVENTION_COLUMN}' not found.")
# return
# # Clean up column names
# df.columns = df.columns.str.strip()
# # Compute Intervention Session Statistics
# intervention_stats = compute_intervention_statistics(df)
# st.subheader("Intervention Session Statistics")
# st.write(intervention_stats)
# # Visualization for Intervention Session Statistics
# plot_intervention_statistics(intervention_stats)
# # Compute Student Metrics
# student_metrics_df = compute_student_metrics(df)
# st.subheader("Student Metrics")
# st.write(student_metrics_df)
# # Visualization for Student Metrics
# plot_student_metrics(student_metrics_df)
# # Prepare input for the language model
# llm_input = prepare_llm_input(student_metrics_df)
# # Generate Notes and Recommendations using Hugging Face LLM
# recommendations = prompt_response_from_hf_llm(llm_input)
# st.subheader("AI Analysis")
# st.markdown(recommendations)
# except Exception as e:
# st.error(f"Error reading the file: {str(e)}")
# def compute_intervention_statistics(df):
# # Total Number of Days Available
# total_days = len(df)
# # Intervention Sessions Held
# sessions_held = df[INTERVENTION_COLUMN].str.strip().str.lower().eq('yes').sum()
# # Intervention Sessions Not Held
# sessions_not_held = df[INTERVENTION_COLUMN].str.strip().str.lower().eq('no').sum()
# # Intervention Frequency (%)
# intervention_frequency = (sessions_held / total_days) * 100 if total_days > 0 else 0
# intervention_frequency = round(intervention_frequency, 2)
# # Create a DataFrame to display the statistics
# stats = {
# 'Total Number of Days Available': [total_days],
# 'Intervention Sessions Held': [sessions_held],
# 'Intervention Sessions Not Held': [sessions_not_held],
# 'Intervention Frequency (%)': [intervention_frequency]
# }
# stats_df = pd.DataFrame(stats)
# return stats_df
# def plot_intervention_statistics(intervention_stats):
# # Create a stacked bar chart for sessions held and not held
# sessions_held = intervention_stats['Intervention Sessions Held'].values[0]
# sessions_not_held = intervention_stats['Intervention Sessions Not Held'].values[0]
# fig, ax = plt.subplots()
# ax.bar(['Intervention Sessions'], [sessions_not_held], label='Not Held', color='#358E66')
# ax.bar(['Intervention Sessions'], [sessions_held], bottom=[sessions_not_held], label='Held', color='#91D6B8')
# # Display the values on the bars
# ax.text(0, sessions_not_held / 2, str(sessions_not_held), ha='center', va='center', color='white')
# ax.text(0, sessions_not_held + sessions_held / 2, str(sessions_held), ha='center', va='center', color='black')
# ax.set_ylabel('Number of Sessions')
# ax.set_title('Intervention Sessions Held vs Not Held')
# ax.legend()
# st.pyplot(fig)
# def compute_student_metrics(df):
# # Filter DataFrame for sessions where intervention happened
# intervention_df = df[df[INTERVENTION_COLUMN].str.strip().str.lower() == 'yes']
# intervention_sessions_held = len(intervention_df)
# # Get list of student columns
# student_columns = [col for col in df.columns if col.startswith('Student Attendance')]
# student_metrics = {}
# for col in student_columns:
# student_name = col.replace('Student Attendance [', '').replace(']', '').strip()
# # Get the attendance data for the student
# student_data = intervention_df[[col]].copy()
# # Treat blank entries as 'Absent'
# student_data[col] = student_data[col].fillna('Absent')
# # Assign attendance values
# attendance_values = student_data[col].apply(lambda x: 1 if x in [
# ENGAGED_STR,
# PARTIALLY_ENGAGED_STR,
# NOT_ENGAGED_STR
# ] else 0)
# # Number of Sessions Attended
# sessions_attended = attendance_values.sum()
# # Attendance (%)
# attendance_pct = (sessions_attended / intervention_sessions_held) * 100 if intervention_sessions_held > 0 else 0
# attendance_pct = round(attendance_pct, 2)
# # For engagement calculation, include only sessions where attendance is not 'Absent'
# valid_engagement_indices = attendance_values[attendance_values == 1].index
# engagement_data = student_data.loc[valid_engagement_indices, col]
# # Assign engagement values
# engagement_values = engagement_data.apply(lambda x: 1 if x == ENGAGED_STR
# else 0.5 if x == PARTIALLY_ENGAGED_STR else 0)
# # Sum of Engagement Values
# sum_engagement_values = engagement_values.sum()
# # Number of Sessions Attended for engagement (should be same as sessions_attended)
# number_sessions_attended = len(valid_engagement_indices)
# # Engagement (%)
# engagement_pct = (sum_engagement_values / number_sessions_attended) * 100 if number_sessions_attended > 0 else 0
# engagement_pct = round(engagement_pct, 2)
# # Store metrics
# student_metrics[student_name] = {
# 'Attendance (%)': attendance_pct,
# 'Engagement (%)': engagement_pct
# }
# # Create a DataFrame from student_metrics
# student_metrics_df = pd.DataFrame.from_dict(student_metrics, orient='index').reset_index()
# student_metrics_df.rename(columns={'index': 'Student'}, inplace=True)
# return student_metrics_df
# def plot_student_metrics(student_metrics_df):
# # Create a line graph for attendance and engagement
# fig, ax = plt.subplots()
# # Plotting Attendance and Engagement with specific colors
# ax.plot(student_metrics_df['Student'], student_metrics_df['Attendance (%)'], marker='o', color='#005288', label='Attendance (%)')
# ax.plot(student_metrics_df['Student'], student_metrics_df['Engagement (%)'], marker='o', color='#3AB0FF', label='Engagement (%)')
# ax.set_xlabel('Student')
# ax.set_ylabel('Percentage (%)')
# ax.set_title('Student Attendance and Engagement Metrics')
# ax.legend()
# plt.xticks(rotation=45)
# st.pyplot(fig)
# def prepare_llm_input(student_metrics_df):
# # Convert the student metrics DataFrame to a string
# metrics_str = student_metrics_df.to_string(index=False)
# llm_input = f"""
# Based on the following student metrics:
# {metrics_str}
# Provide:
# 1. Notes and Key Takeaways: Summarize the data, highlight students with the lowest and highest attendance and engagement percentages, identify students who may need adjustments to their intervention due to low attendance or engagement, and highlight students who are showing strong performance.
# 2. Recommendations and Next Steps: Provide interpretations based on the analysis and suggest possible next steps or strategies to improve student outcomes.
# """
# return llm_input
# def prompt_response_from_hf_llm(llm_input):
# # Generate the refined prompt using Hugging Face API
# response = client.chat.completions.create(
# # model="mistralai/Mistral-7B-Instruct-v0.3",
# model="meta-llama/Llama-3.1-70B-Instruct",
# messages=[
# {"role": "user", "content": llm_input}
# ],
# stream=True,
# temperature=0.5,
# max_tokens=1024,
# top_p=0.7
# )
# # Combine messages if response is streamed
# response_content = ""
# for message in response:
# response_content += message.choices[0].delta.content
# return response_content.strip()
# if __name__ == '__main__':
# main()
# CHARTS + DOWNLOAD
# # intervention_analysis_app.py
# import streamlit as st
# import pandas as pd
# import matplotlib.pyplot as plt
# import io
# # from transformers import pipeline
# from huggingface_hub import InferenceClient
# import os
# from pathlib import Path
# from dotenv import load_dotenv
# load_dotenv()
# # Set the Hugging Face API key
# # Retrieve Hugging Face API key from environment variables
# hf_api_key = os.getenv('HF_API_KEY')
# if not hf_api_key:
# raise ValueError("HF_API_KEY not set in environment variables")
# # Create the Hugging Face inference client
# client = InferenceClient(api_key=hf_api_key)
# # Constants
# INTERVENTION_COLUMN = 'Did the intervention happen today?'
# ENGAGED_STR = 'Engaged (Respect, Responsibility, Effort)'
# PARTIALLY_ENGAGED_STR = 'Partially Engaged (about 50%)'
# NOT_ENGAGED_STR = 'Not Engaged (less than 50%)'
# def main():
# st.title("Intervention Program Analysis")
# # File uploader
# uploaded_file = st.file_uploader("Upload your Excel file", type=["xlsx"])
# if uploaded_file is not None:
# try:
# # Read the Excel file into a DataFrame
# df = pd.read_excel(uploaded_file)
# st.subheader("Uploaded Data")
# st.write(df.head(4)) # Display only the first four rows
# # Ensure expected column is available
# if INTERVENTION_COLUMN not in df.columns:
# st.error(f"Expected column '{INTERVENTION_COLUMN}' not found.")
# return
# # Clean up column names
# df.columns = df.columns.str.strip()
# # Compute Intervention Session Statistics
# intervention_stats = compute_intervention_statistics(df)
# st.subheader("Intervention Session Statistics")
# st.write(intervention_stats)
# # Visualization for Intervention Session Statistics
# intervention_fig = plot_intervention_statistics(intervention_stats)
# # Add download button for Intervention Session Statistics chart
# download_chart(intervention_fig, "intervention_statistics_chart.png")
# # Compute Student Metrics
# student_metrics_df = compute_student_metrics(df)
# st.subheader("Student Metrics")
# st.write(student_metrics_df)
# # Visualization for Student Metrics
# student_metrics_fig = plot_student_metrics(student_metrics_df)
# # Add download button for Student Metrics chart
# download_chart(student_metrics_fig, "student_metrics_chart.png")
# # Prepare input for the language model
# llm_input = prepare_llm_input(student_metrics_df)
# # Generate Notes and Recommendations using Hugging Face LLM
# with st.spinner("Generating AI analysis..."):
# recommendations = prompt_response_from_hf_llm(llm_input)
# st.subheader("AI Analysis")
# st.markdown(recommendations)
# # Add download button for LLM output
# download_llm_output(recommendations, "llm_output.txt")
# except Exception as e:
# st.error(f"Error reading the file: {str(e)}")
# def compute_intervention_statistics(df):
# # Total Number of Days Available
# total_days = len(df)
# # Intervention Sessions Held
# sessions_held = df[INTERVENTION_COLUMN].str.strip().str.lower().eq('yes').sum()
# # Intervention Sessions Not Held
# sessions_not_held = df[INTERVENTION_COLUMN].str.strip().str.lower().eq('no').sum()
# # Intervention Frequency (%)
# intervention_frequency = (sessions_held / total_days) * 100 if total_days > 0 else 0
# intervention_frequency = round(intervention_frequency, 2)
# # Create a DataFrame to display the statistics
# stats = {
# 'Total Number of Days Available': [total_days],
# 'Intervention Sessions Held': [sessions_held],
# 'Intervention Sessions Not Held': [sessions_not_held],
# 'Intervention Frequency (%)': [intervention_frequency]
# }
# stats_df = pd.DataFrame(stats)
# return stats_df
# def plot_intervention_statistics(intervention_stats):
# # Create a stacked bar chart for sessions held and not held
# sessions_held = intervention_stats['Intervention Sessions Held'].values[0]
# sessions_not_held = intervention_stats['Intervention Sessions Not Held'].values[0]
# fig, ax = plt.subplots()
# ax.bar(['Intervention Sessions'], [sessions_not_held], label='Not Held', color='#358E66')
# ax.bar(['Intervention Sessions'], [sessions_held], bottom=[sessions_not_held], label='Held', color='#91D6B8')
# # Display the values on the bars
# ax.text(0, sessions_not_held / 2, str(sessions_not_held), ha='center', va='center', color='white')
# ax.text(0, sessions_not_held + sessions_held / 2, str(sessions_held), ha='center', va='center', color='black')
# ax.set_ylabel('Number of Sessions')
# ax.set_title('Intervention Sessions Held vs Not Held')
# ax.legend()
# st.pyplot(fig)
# return fig
# def compute_student_metrics(df):
# # Filter DataFrame for sessions where intervention happened
# intervention_df = df[df[INTERVENTION_COLUMN].str.strip().str.lower() == 'yes']
# intervention_sessions_held = len(intervention_df)
# # Get list of student columns
# student_columns = [col for col in df.columns if col.startswith('Student Attendance')]
# student_metrics = {}
# for col in student_columns:
# student_name = col.replace('Student Attendance [', '').replace(']', '').strip()
# # Get the attendance data for the student
# student_data = intervention_df[[col]].copy()
# # Treat blank entries as 'Absent'
# student_data[col] = student_data[col].fillna('Absent')
# # Assign attendance values
# attendance_values = student_data[col].apply(lambda x: 1 if x in [
# ENGAGED_STR,
# PARTIALLY_ENGAGED_STR,
# NOT_ENGAGED_STR
# ] else 0)
# # Number of Sessions Attended
# sessions_attended = attendance_values.sum()
# # Attendance (%)
# attendance_pct = (sessions_attended / intervention_sessions_held) * 100 if intervention_sessions_held > 0 else 0
# attendance_pct = round(attendance_pct, 2)
# # For engagement calculation, include only sessions where attendance is not 'Absent'
# valid_engagement_indices = attendance_values[attendance_values == 1].index
# engagement_data = student_data.loc[valid_engagement_indices, col]
# # Assign engagement values
# engagement_values = engagement_data.apply(lambda x: 1 if x == ENGAGED_STR
# else 0.5 if x == PARTIALLY_ENGAGED_STR else 0)
# # Sum of Engagement Values
# sum_engagement_values = engagement_values.sum()
# # Number of Sessions Attended for engagement (should be same as sessions_attended)
# number_sessions_attended = len(valid_engagement_indices)
# # Engagement (%)
# engagement_pct = (sum_engagement_values / number_sessions_attended) * 100 if number_sessions_attended > 0 else 0
# engagement_pct = round(engagement_pct, 2)
# # Store metrics
# student_metrics[student_name] = {
# 'Attendance (%)': attendance_pct,
# 'Engagement (%)': engagement_pct
# }
# # Create a DataFrame from student_metrics
# student_metrics_df = pd.DataFrame.from_dict(student_metrics, orient='index').reset_index()
# student_metrics_df.rename(columns={'index': 'Student'}, inplace=True)
# return student_metrics_df
# def plot_student_metrics(student_metrics_df):
# # Create a line graph for attendance and engagement
# fig, ax = plt.subplots()
# # Plotting Attendance and Engagement with specific colors
# ax.plot(student_metrics_df['Student'], student_metrics_df['Attendance (%)'], marker='o', color='#005288', label='Attendance (%)')
# ax.plot(student_metrics_df['Student'], student_metrics_df['Engagement (%)'], marker='o', color='#3AB0FF', label='Engagement (%)')
# ax.set_xlabel('Student')
# ax.set_ylabel('Percentage (%)')
# ax.set_title('Student Attendance and Engagement Metrics')
# ax.legend()
# plt.xticks(rotation=45)
# st.pyplot(fig)
# return fig
# def download_chart(fig, filename):
# # Create a buffer to hold the image data
# buffer = io.BytesIO()
# # Save the figure to the buffer
# fig.savefig(buffer, format='png')
# # Set the file pointer to the beginning
# buffer.seek(0)
# # Add a download button to Streamlit
# st.download_button(label="Download Chart", data=buffer, file_name=filename, mime='image/png')
# def download_llm_output(content, filename):
# # Create a buffer to hold the text data
# buffer = io.BytesIO()
# buffer.write(content.encode('utf-8'))
# buffer.seek(0)
# # Add a download button to Streamlit
# st.download_button(label="Download LLM Output", data=buffer, file_name=filename, mime='text/plain')
# def prepare_llm_input(student_metrics_df):
# # Convert the student metrics DataFrame to a string
# metrics_str = student_metrics_df.to_string(index=False)
# llm_input = f"""
# Based on the following student metrics:
# {metrics_str}
# Provide:
# 1. Notes and Key Takeaways: Summarize the data, highlight students with the lowest and highest attendance and engagement percentages, identify students who may need adjustments to their intervention due to low attendance or engagement, and highlight students who are showing strong performance.
# 2. Recommendations and Next Steps: Provide interpretations based on the analysis and suggest possible next steps or strategies to improve student outcomes.
# """
# return llm_input
# def prompt_response_from_hf_llm(llm_input):
# # Generate the refined prompt using Hugging Face API
# response = client.chat.completions.create(
# model="meta-llama/Llama-3.1-70B-Instruct",
# messages=[
# {"role": "user", "content": llm_input}
# ],
# stream=True,
# temperature=0.5,
# max_tokens=1024,
# top_p=0.7
# )
# # Combine messages if response is streamed
# response_content = ""
# for message in response:
# response_content += message.choices[0].delta.content
# return response_content.strip()
# if __name__ == '__main__':
# main()
# CHARTS + DOWNLOAD + NO NAMES
# intervention_analysis_app.py
#------------------------------------------------------------------------
# Import Modules
#------------------------------------------------------------------------
import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
import io
import re
# from transformers import pipeline
from huggingface_hub import InferenceClient
import os
from pathlib import Path
from dotenv import load_dotenv
load_dotenv()
#------------------------------------------------------------------------
# Configurations
#------------------------------------------------------------------------
# Streamlit page setup
st.set_page_config(
page_title="Intervention Program Analysis",
page_icon=":bar_chart:",
layout="centered",
initial_sidebar_state="auto",
menu_items={
'Get Help': 'mailto:[email protected]',
'About': "This app is built to support spreadsheet analysis"
}
)
#------------------------------------------------------------------------
# Sidebar
#------------------------------------------------------------------------
with st.sidebar:
# Password input field
# password = st.text_input("Enter Password:", type="password")
# Set the desired width in pixels
image_width = 300
# Define the path to the image
image_path = "/Users/cheynelevesseur/Desktop/Manual Library/Python_Code/LLM_Projects_1/intervention_analysis_app/mimtss_logo.png"
# Display the image
st.image(image_path, width=image_width)
# Toggle for Help and Report a Bug
with st.expander("Need help and report a bug"):
st.write("""
**Contact**: Cheyne LeVesseur, PhD
**Email**: [email protected]
""")
st.divider()
st.subheader('User Instructions')
# Principles text with Markdown formatting
User_Instructions = """
- **Step 1**: Upload your Excel file.
- **Step 2**: Anonymization – student names are replaced with initials for privacy.
- **Step 3**: Review anonymized data.
- **Step 4**: View **intervention session statistics**.
- **Step 5**: Review **student attendance and engagement metrics**.
- **Step 6**: Review AI-generated **insights and recommendations**.
### **Privacy Assurance**
- **No full names** are ever displayed or sent to the AI model—only initials are used.
- This ensures that sensitive data remains protected throughout the entire process.
### **Detailed Instructions**
#### **1. Upload Your Excel File**
- Start by uploading an Excel file that contains intervention data.
- Click on the **“Upload your Excel file”** button and select your `.xlsx` file from your computer.
**Note**: Your file should have columns like "Did the intervention happen today?" and "Student Attendance [FirstName LastName]" for the analysis to work correctly.
#### **2. Automated Name Anonymization**
- Once the file is uploaded, the app will **automatically replace student names with initials** in the "Student Attendance" columns.
- For example, **"Student Attendance [Cheyne LeVesseur]"** will be displayed as **"Student Attendance [CL]"**.
- If the student only has a first name, like **"Student Attendance [Cheyne]"**, it will be displayed as **"Student Attendance [C]"**.
- This anonymization helps to **protect student privacy**, ensuring that full names are not visible or sent to the AI language model.
#### **3. Review the Uploaded Data**
- You will see the entire table of anonymized data to verify that the information has been uploaded correctly and that names have been replaced with initials.
#### **4. Intervention Session Statistics**
- The app will calculate and display statistics related to intervention sessions, such as:
- **Total Number of Days Available**
- **Intervention Sessions Held**
- **Intervention Sessions Not Held**
- **Intervention Frequency (%)**
- A **stacked bar chart** will be shown to visualize the number of sessions held versus not held.
- If you need to save the visualization, click the **“Download Chart”** button to download it as a `.png` file.
#### **5. Student Metrics Analysis**
- The app will also calculate metrics for each student:
- **Attendance (%)** – The percentage of intervention sessions attended.
- **Engagement (%)** – The level of engagement during attended sessions.
- These metrics will be presented in a **line graph** that shows attendance and engagement for each student.
- You can click the **“Download Chart”** button to download the visualization as a `.png` file.
#### **6. Generate AI Analysis and Recommendations**
- The app will prepare data from the student metrics to provide notes, key takeaways, and suggestions for improving outcomes using an **AI language model**.
- You will see a **spinner** labeled **“Generating AI analysis…”** while the AI processes the data.
- This step may take a little longer, but the spinner ensures you know that the system is working.
- Once the analysis is complete, the AI's recommendations will be displayed under **"AI Analysis"**.
- You can click the **“Download LLM Output”** button to download the AI-generated recommendations as a `.txt` file for future reference.
"""
st.markdown(User_Instructions)
#------------------------------------------------------------------------
# Functions
#------------------------------------------------------------------------
# Set the Hugging Face API key
# Retrieve Hugging Face API key from environment variables
hf_api_key = os.getenv('HF_API_KEY')
if not hf_api_key:
raise ValueError("HF_API_KEY not set in environment variables")
# Create the Hugging Face inference client
client = InferenceClient(api_key=hf_api_key)
# Constants
INTERVENTION_COLUMN = 'Did the intervention happen today?'
ENGAGED_STR = 'Engaged (Respect, Responsibility, Effort)'
PARTIALLY_ENGAGED_STR = 'Partially Engaged (about 50%)'
NOT_ENGAGED_STR = 'Not Engaged (less than 50%)'
def main():
st.title("Intervention Program Analysis")
# File uploader
uploaded_file = st.file_uploader("Upload your Excel file", type=["xlsx"])
if uploaded_file is not None:
try:
# Read the Excel file into a DataFrame
df = pd.read_excel(uploaded_file)
# Replace student names with initials
df = replace_student_names_with_initials(df)
st.subheader("Uploaded Data")
st.write(df.head(4)) # Display only the first four rows
# Ensure expected column is available
if INTERVENTION_COLUMN not in df.columns:
st.error(f"Expected column '{INTERVENTION_COLUMN}' not found.")
return
# Clean up column names
df.columns = df.columns.str.strip()
# Compute Intervention Session Statistics
intervention_stats = compute_intervention_statistics(df)
st.subheader("Intervention Session Statistics")
st.write(intervention_stats)
# Visualization for Intervention Session Statistics
intervention_fig = plot_intervention_statistics(intervention_stats)
# Add download button for Intervention Session Statistics chart
download_chart(intervention_fig, "intervention_statistics_chart.png")
# Compute Student Metrics
student_metrics_df = compute_student_metrics(df)
st.subheader("Student Metrics")
st.write(student_metrics_df)
# Visualization for Student Metrics
student_metrics_fig = plot_student_metrics(student_metrics_df)
# Add download button for Student Metrics chart
download_chart(student_metrics_fig, "student_metrics_chart.png")
# Prepare input for the language model
llm_input = prepare_llm_input(student_metrics_df)
# Generate Notes and Recommendations using Hugging Face LLM
with st.spinner("Generating AI analysis..."):
recommendations = prompt_response_from_hf_llm(llm_input)
st.subheader("AI Analysis")
st.markdown(recommendations)
# Add download button for LLM output
download_llm_output(recommendations, "llm_output.txt")
except Exception as e:
st.error(f"Error reading the file: {str(e)}")
def replace_student_names_with_initials(df):
"""Replace student names in column headers with initials."""
updated_columns = []
for col in df.columns:
if col.startswith('Student Attendance'):
# Extract the name from the column header
match = re.match(r'Student Attendance \[(.+?)\]', col)
if match:
name = match.group(1)
# Split the name into parts (first and last name)
name_parts = name.split()
# Convert the name to initials
if len(name_parts) == 1:
initials = name_parts[0][0] # Just take the first letter
else:
initials = ''.join([part[0] for part in name_parts]) # Take the first letter of each part
# Update the column name
updated_columns.append(f'Student Attendance [{initials}]')
else:
updated_columns.append(col)
else:
updated_columns.append(col)
df.columns = updated_columns
return df
def compute_intervention_statistics(df):
# Total Number of Days Available
total_days = len(df)
# Intervention Sessions Held
sessions_held = df[INTERVENTION_COLUMN].str.strip().str.lower().eq('yes').sum()
# Intervention Sessions Not Held
sessions_not_held = df[INTERVENTION_COLUMN].str.strip().str.lower().eq('no').sum()
# Intervention Frequency (%)
intervention_frequency = (sessions_held / total_days) * 100 if total_days > 0 else 0
intervention_frequency = round(intervention_frequency, 2)
# Create a DataFrame to display the statistics
stats = {
'Total Number of Days Available': [total_days],
'Intervention Sessions Held': [sessions_held],
'Intervention Sessions Not Held': [sessions_not_held],
'Intervention Frequency (%)': [intervention_frequency]
}
stats_df = pd.DataFrame(stats)
return stats_df
def plot_intervention_statistics(intervention_stats):
# Create a stacked bar chart for sessions held and not held
sessions_held = intervention_stats['Intervention Sessions Held'].values[0]
sessions_not_held = intervention_stats['Intervention Sessions Not Held'].values[0]
fig, ax = plt.subplots()
ax.bar(['Intervention Sessions'], [sessions_not_held], label='Not Held', color='#358E66')
ax.bar(['Intervention Sessions'], [sessions_held], bottom=[sessions_not_held], label='Held', color='#91D6B8')
# Display the values on the bars
ax.text(0, sessions_not_held / 2, str(sessions_not_held), ha='center', va='center', color='white')
ax.text(0, sessions_not_held + sessions_held / 2, str(sessions_held), ha='center', va='center', color='black')
ax.set_ylabel('Number of Sessions')
ax.set_title('Intervention Sessions Held vs Not Held')
ax.legend()
st.pyplot(fig)
return fig
def compute_student_metrics(df):
# Filter DataFrame for sessions where intervention happened
intervention_df = df[df[INTERVENTION_COLUMN].str.strip().str.lower() == 'yes']
intervention_sessions_held = len(intervention_df)
# Get list of student columns
student_columns = [col for col in df.columns if col.startswith('Student Attendance')]
student_metrics = {}
for col in student_columns:
student_name = col.replace('Student Attendance [', '').replace(']', '').strip()
# Get the attendance data for the student
student_data = intervention_df[[col]].copy()
# Treat blank entries as 'Absent'
student_data[col] = student_data[col].fillna('Absent')
# Assign attendance values
attendance_values = student_data[col].apply(lambda x: 1 if x in [
ENGAGED_STR,
PARTIALLY_ENGAGED_STR,
NOT_ENGAGED_STR
] else 0)
# Number of Sessions Attended
sessions_attended = attendance_values.sum()
# Attendance (%)
attendance_pct = (sessions_attended / intervention_sessions_held) * 100 if intervention_sessions_held > 0 else 0
attendance_pct = round(attendance_pct, 2)
# For engagement calculation, include only sessions where attendance is not 'Absent'
valid_engagement_indices = attendance_values[attendance_values == 1].index
engagement_data = student_data.loc[valid_engagement_indices, col]
# Assign engagement values
engagement_values = engagement_data.apply(lambda x: 1 if x == ENGAGED_STR
else 0.5 if x == PARTIALLY_ENGAGED_STR else 0)
# Sum of Engagement Values
sum_engagement_values = engagement_values.sum()
# Number of Sessions Attended for engagement (should be same as sessions_attended)
number_sessions_attended = len(valid_engagement_indices)
# Engagement (%)
engagement_pct = (sum_engagement_values / number_sessions_attended) * 100 if number_sessions_attended > 0 else 0
engagement_pct = round(engagement_pct, 2)
# Store metrics
student_metrics[student_name] = {
'Attendance (%)': attendance_pct,
'Engagement (%)': engagement_pct
}
# Create a DataFrame from student_metrics
student_metrics_df = pd.DataFrame.from_dict(student_metrics, orient='index').reset_index()
student_metrics_df.rename(columns={'index': 'Student'}, inplace=True)
return student_metrics_df
def plot_student_metrics(student_metrics_df):
# Create a line graph for attendance and engagement
fig, ax = plt.subplots()
# Plotting Attendance and Engagement with specific colors
ax.plot(student_metrics_df['Student'], student_metrics_df['Attendance (%)'], marker='o', color='#005288', label='Attendance (%)')
ax.plot(student_metrics_df['Student'], student_metrics_df['Engagement (%)'], marker='o', color='#3AB0FF', label='Engagement (%)')
ax.set_xlabel('Student')
ax.set_ylabel('Percentage (%)')
ax.set_title('Student Attendance and Engagement Metrics')
ax.legend()
plt.xticks(rotation=45)
st.pyplot(fig)
return fig
def download_chart(fig, filename):
# Create a buffer to hold the image data
buffer = io.BytesIO()
# Save the figure to the buffer
fig.savefig(buffer, format='png')
# Set the file pointer to the beginning
buffer.seek(0)
# Add a download button to Streamlit
st.download_button(label="Download Chart", data=buffer, file_name=filename, mime='image/png')
def download_llm_output(content, filename):
# Create a buffer to hold the text data
buffer = io.BytesIO()
buffer.write(content.encode('utf-8'))
buffer.seek(0)
# Add a download button to Streamlit
st.download_button(label="Download LLM Output", data=buffer, file_name=filename, mime='text/plain')
def prepare_llm_input(student_metrics_df):
# Convert the student metrics DataFrame to a string
metrics_str = student_metrics_df.to_string(index=False)
llm_input = f"""
Based on the following student metrics:
{metrics_str}
Provide:
1. Notes and Key Takeaways: Summarize the data, highlight students with the lowest and highest attendance and engagement percentages, identify students who may need adjustments to their intervention due to low attendance or engagement, and highlight students who are showing strong performance.
2. Recommendations and Next Steps: Provide interpretations based on the analysis and suggest possible next steps or strategies to improve student outcomes.
"""
return llm_input
def prompt_response_from_hf_llm(llm_input):
# Generate the refined prompt using Hugging Face API
response = client.chat.completions.create(
model="meta-llama/Llama-3.1-70B-Instruct",
messages=[
{"role": "user", "content": llm_input}
],
stream=True,
temperature=0.5,
max_tokens=1024,
top_p=0.7
)
# Combine messages if response is streamed
response_content = ""
for message in response:
response_content += message.choices[0].delta.content
return response_content.strip()
if __name__ == '__main__':
main() |