ProfessorLeVesseur commited on
Commit
d8776ec
·
verified ·
1 Parent(s): e157853

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -400
app.py DELETED
@@ -1,400 +0,0 @@
1
- # CHARTS + DOWNLOAD + NO NAMES
2
- # intervention_analysis_app.py
3
-
4
- #------------------------------------------------------------------------
5
- # Import Modules
6
- #------------------------------------------------------------------------
7
- import streamlit as st
8
- import pandas as pd
9
- import matplotlib.pyplot as plt
10
- import io
11
- import re
12
- # from transformers import pipeline
13
- from huggingface_hub import InferenceClient
14
- import os
15
- from pathlib import Path
16
- from dotenv import load_dotenv
17
-
18
- load_dotenv()
19
-
20
- #------------------------------------------------------------------------
21
- # Configurations
22
- #------------------------------------------------------------------------
23
- # Streamlit page setup
24
- st.set_page_config(
25
- page_title="Intervention Program Analysis",
26
- page_icon=":bar_chart:",
27
- layout="centered",
28
- initial_sidebar_state="auto",
29
- menu_items={
30
- 'Get Help': 'mailto:[email protected]',
31
- 'About': "This app is built to support spreadsheet analysis"
32
- }
33
- )
34
-
35
- #------------------------------------------------------------------------
36
- # Sidebar
37
- #------------------------------------------------------------------------
38
- with st.sidebar:
39
- # Password input field
40
- # password = st.text_input("Enter Password:", type="password")
41
-
42
- # Set the desired width in pixels
43
- image_width = 300
44
- # Define the path to the image
45
- image_path = "mimtss.png"
46
- # Display the image
47
- st.image(image_path, width=image_width)
48
-
49
- # Toggle for Help and Report a Bug
50
- with st.expander("Need help and report a bug"):
51
- st.write("""
52
- **Contact**: Cheyne LeVesseur, PhD
53
- **Email**: [email protected]
54
- """)
55
- st.divider()
56
- st.subheader('User Instructions')
57
-
58
- # Principles text with Markdown formatting
59
- User_Instructions = """
60
-
61
- - **Step 1**: Upload your Excel file.
62
- - **Step 2**: Anonymization – student names are replaced with initials for privacy.
63
- - **Step 3**: Review anonymized data.
64
- - **Step 4**: View **intervention session statistics**.
65
- - **Step 5**: Review **student attendance and engagement metrics**.
66
- - **Step 6**: Review AI-generated **insights and recommendations**.
67
-
68
- ### **Privacy Assurance**
69
- - **No full names** are ever displayed or sent to the AI model—only initials are used.
70
- - This ensures that sensitive data remains protected throughout the entire process.
71
-
72
- ### **Detailed Instructions**
73
-
74
- #### **1. Upload Your Excel File**
75
- - Start by uploading an Excel file that contains intervention data.
76
- - Click on the **“Upload your Excel file”** button and select your `.xlsx` file from your computer.
77
-
78
- **Note**: Your file should have columns like "Did the intervention happen today?" and "Student Attendance [FirstName LastName]" for the analysis to work correctly.
79
-
80
- #### **2. Automated Name Anonymization**
81
- - Once the file is uploaded, the app will **automatically replace student names with initials** in the "Student Attendance" columns.
82
- - For example, **"Student Attendance [Cheyne LeVesseur]"** will be displayed as **"Student Attendance [CL]"**.
83
- - If the student only has a first name, like **"Student Attendance [Cheyne]"**, it will be displayed as **"Student Attendance [C]"**.
84
- - This anonymization helps to **protect student privacy**, ensuring that full names are not visible or sent to the AI language model.
85
-
86
- #### **3. Review the Uploaded Data**
87
- - 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.
88
-
89
- #### **4. Intervention Session Statistics**
90
- - The app will calculate and display statistics related to intervention sessions, such as:
91
- - **Total Number of Days Available**
92
- - **Intervention Sessions Held**
93
- - **Intervention Sessions Not Held**
94
- - **Intervention Frequency (%)**
95
- - A **stacked bar chart** will be shown to visualize the number of sessions held versus not held.
96
- - If you need to save the visualization, click the **“Download Chart”** button to download it as a `.png` file.
97
-
98
- #### **5. Student Metrics Analysis**
99
- - The app will also calculate metrics for each student:
100
- - **Attendance (%)** – The percentage of intervention sessions attended.
101
- - **Engagement (%)** – The level of engagement during attended sessions.
102
- - These metrics will be presented in a **line graph** that shows attendance and engagement for each student.
103
- - You can click the **“Download Chart”** button to download the visualization as a `.png` file.
104
-
105
- #### **6. Generate AI Analysis and Recommendations**
106
- - The app will prepare data from the student metrics to provide notes, key takeaways, and suggestions for improving outcomes using an **AI language model**.
107
- - You will see a **spinner** labeled **“Generating AI analysis…”** while the AI processes the data.
108
- - This step may take a little longer, but the spinner ensures you know that the system is working.
109
- - Once the analysis is complete, the AI's recommendations will be displayed under **"AI Analysis"**.
110
- - You can click the **“Download LLM Output”** button to download the AI-generated recommendations as a `.txt` file for future reference.
111
-
112
- """
113
- st.markdown(User_Instructions)
114
-
115
- #------------------------------------------------------------------------
116
- # Functions
117
- #------------------------------------------------------------------------
118
- # Set the Hugging Face API key
119
- # Retrieve Hugging Face API key from environment variables
120
- hf_api_key = os.getenv('HF_API_KEY')
121
- if not hf_api_key:
122
- raise ValueError("HF_API_KEY not set in environment variables")
123
-
124
- # Create the Hugging Face inference client
125
- client = InferenceClient(api_key=hf_api_key)
126
-
127
- # Constants
128
- INTERVENTION_COLUMN = 'Did the intervention happen today?'
129
- ENGAGED_STR = 'Engaged (Respect, Responsibility, Effort)'
130
- PARTIALLY_ENGAGED_STR = 'Partially Engaged (about 50%)'
131
- NOT_ENGAGED_STR = 'Not Engaged (less than 50%)'
132
-
133
- def main():
134
- st.title("Intervention Program Analysis")
135
-
136
- # File uploader
137
- uploaded_file = st.file_uploader("Upload your Excel file", type=["xlsx"])
138
-
139
- if uploaded_file is not None:
140
- try:
141
- # Read the Excel file into a DataFrame
142
- df = pd.read_excel(uploaded_file)
143
-
144
- # Replace student names with initials
145
- df = replace_student_names_with_initials(df)
146
-
147
- st.subheader("Uploaded Data")
148
- st.write(df) # Display only the first four rows
149
-
150
- # Ensure expected column is available
151
- if INTERVENTION_COLUMN not in df.columns:
152
- st.error(f"Expected column '{INTERVENTION_COLUMN}' not found.")
153
- return
154
-
155
- # Clean up column names
156
- df.columns = df.columns.str.strip()
157
-
158
- # Compute Intervention Session Statistics
159
- intervention_stats = compute_intervention_statistics(df)
160
- st.subheader("Intervention Session Statistics")
161
- st.write(intervention_stats)
162
-
163
- # Visualization for Intervention Session Statistics
164
- intervention_fig = plot_intervention_statistics(intervention_stats)
165
-
166
- # Add download button for Intervention Session Statistics chart
167
- download_chart(intervention_fig, "intervention_statistics_chart.png")
168
-
169
- # Compute Student Metrics
170
- student_metrics_df = compute_student_metrics(df)
171
- st.subheader("Student Metrics")
172
- st.write(student_metrics_df)
173
-
174
- # Visualization for Student Metrics
175
- student_metrics_fig = plot_student_metrics(student_metrics_df)
176
-
177
- # Add download button for Student Metrics chart
178
- download_chart(student_metrics_fig, "student_metrics_chart.png")
179
-
180
- # Prepare input for the language model
181
- llm_input = prepare_llm_input(student_metrics_df)
182
-
183
- # Generate Notes and Recommendations using Hugging Face LLM
184
- with st.spinner("Generating AI analysis..."):
185
- recommendations = prompt_response_from_hf_llm(llm_input)
186
-
187
- st.subheader("AI Analysis")
188
- st.markdown(recommendations)
189
-
190
- # Add download button for LLM output
191
- download_llm_output(recommendations, "llm_output.txt")
192
-
193
- except Exception as e:
194
- st.error(f"Error reading the file: {str(e)}")
195
-
196
- def replace_student_names_with_initials(df):
197
- """Replace student names in column headers with initials."""
198
- updated_columns = []
199
- for col in df.columns:
200
- if col.startswith('Student Attendance'):
201
- # Extract the name from the column header
202
- match = re.match(r'Student Attendance \[(.+?)\]', col)
203
- if match:
204
- name = match.group(1)
205
- # Split the name into parts (first and last name)
206
- name_parts = name.split()
207
- # Convert the name to initials
208
- if len(name_parts) == 1:
209
- initials = name_parts[0][0] # Just take the first letter
210
- else:
211
- initials = ''.join([part[0] for part in name_parts]) # Take the first letter of each part
212
- # Update the column name
213
- updated_columns.append(f'Student Attendance [{initials}]')
214
- else:
215
- updated_columns.append(col)
216
- else:
217
- updated_columns.append(col)
218
- df.columns = updated_columns
219
- return df
220
-
221
- def compute_intervention_statistics(df):
222
- # Total Number of Days Available
223
- total_days = len(df)
224
-
225
- # Intervention Sessions Held
226
- sessions_held = df[INTERVENTION_COLUMN].str.strip().str.lower().eq('yes').sum()
227
-
228
- # Intervention Sessions Not Held
229
- sessions_not_held = df[INTERVENTION_COLUMN].str.strip().str.lower().eq('no').sum()
230
-
231
- # Intervention Frequency (%)
232
- intervention_frequency = (sessions_held / total_days) * 100 if total_days > 0 else 0
233
- intervention_frequency = round(intervention_frequency, 2)
234
-
235
- # Create a DataFrame to display the statistics
236
- stats = {
237
- 'Total Number of Days Available': [total_days],
238
- 'Intervention Sessions Held': [sessions_held],
239
- 'Intervention Sessions Not Held': [sessions_not_held],
240
- 'Intervention Frequency (%)': [intervention_frequency]
241
- }
242
- stats_df = pd.DataFrame(stats)
243
- return stats_df
244
-
245
- def plot_intervention_statistics(intervention_stats):
246
- # Create a stacked bar chart for sessions held and not held
247
- sessions_held = intervention_stats['Intervention Sessions Held'].values[0]
248
- sessions_not_held = intervention_stats['Intervention Sessions Not Held'].values[0]
249
-
250
- fig, ax = plt.subplots()
251
- ax.bar(['Intervention Sessions'], [sessions_not_held], label='Not Held', color='#358E66')
252
- ax.bar(['Intervention Sessions'], [sessions_held], bottom=[sessions_not_held], label='Held', color='#91D6B8')
253
-
254
- # Display the values on the bars
255
- ax.text(0, sessions_not_held / 2, str(sessions_not_held), ha='center', va='center', color='white')
256
- ax.text(0, sessions_not_held + sessions_held / 2, str(sessions_held), ha='center', va='center', color='black')
257
-
258
- ax.set_ylabel('Number of Sessions')
259
- ax.set_title('Intervention Sessions Held vs Not Held')
260
- ax.legend()
261
-
262
- st.pyplot(fig)
263
-
264
- return fig
265
-
266
- def compute_student_metrics(df):
267
- # Filter DataFrame for sessions where intervention happened
268
- intervention_df = df[df[INTERVENTION_COLUMN].str.strip().str.lower() == 'yes']
269
- intervention_sessions_held = len(intervention_df)
270
-
271
- # Get list of student columns
272
- student_columns = [col for col in df.columns if col.startswith('Student Attendance')]
273
-
274
- student_metrics = {}
275
-
276
- for col in student_columns:
277
- student_name = col.replace('Student Attendance [', '').replace(']', '').strip()
278
- # Get the attendance data for the student
279
- student_data = intervention_df[[col]].copy()
280
-
281
- # Treat blank entries as 'Absent'
282
- student_data[col] = student_data[col].fillna('Absent')
283
-
284
- # Assign attendance values
285
- attendance_values = student_data[col].apply(lambda x: 1 if x in [
286
- ENGAGED_STR,
287
- PARTIALLY_ENGAGED_STR,
288
- NOT_ENGAGED_STR
289
- ] else 0)
290
-
291
- # Number of Sessions Attended
292
- sessions_attended = attendance_values.sum()
293
-
294
- # Attendance (%)
295
- attendance_pct = (sessions_attended / intervention_sessions_held) * 100 if intervention_sessions_held > 0 else 0
296
- attendance_pct = round(attendance_pct, 2)
297
-
298
- # For engagement calculation, include only sessions where attendance is not 'Absent'
299
- valid_engagement_indices = attendance_values[attendance_values == 1].index
300
- engagement_data = student_data.loc[valid_engagement_indices, col]
301
-
302
- # Assign engagement values
303
- engagement_values = engagement_data.apply(lambda x: 1 if x == ENGAGED_STR
304
- else 0.5 if x == PARTIALLY_ENGAGED_STR else 0)
305
-
306
- # Sum of Engagement Values
307
- sum_engagement_values = engagement_values.sum()
308
-
309
- # Number of Sessions Attended for engagement (should be same as sessions_attended)
310
- number_sessions_attended = len(valid_engagement_indices)
311
-
312
- # Engagement (%)
313
- engagement_pct = (sum_engagement_values / number_sessions_attended) * 100 if number_sessions_attended > 0 else 0
314
- engagement_pct = round(engagement_pct, 2)
315
-
316
- # Store metrics
317
- student_metrics[student_name] = {
318
- 'Attendance (%)': attendance_pct,
319
- 'Engagement (%)': engagement_pct
320
- }
321
-
322
- # Create a DataFrame from student_metrics
323
- student_metrics_df = pd.DataFrame.from_dict(student_metrics, orient='index').reset_index()
324
- student_metrics_df.rename(columns={'index': 'Student'}, inplace=True)
325
- return student_metrics_df
326
-
327
- def plot_student_metrics(student_metrics_df):
328
- # Create a line graph for attendance and engagement
329
- fig, ax = plt.subplots()
330
-
331
- # Plotting Attendance and Engagement with specific colors
332
- ax.plot(student_metrics_df['Student'], student_metrics_df['Attendance (%)'], marker='o', color='#005288', label='Attendance (%)')
333
- ax.plot(student_metrics_df['Student'], student_metrics_df['Engagement (%)'], marker='o', color='#3AB0FF', label='Engagement (%)')
334
-
335
- ax.set_xlabel('Student')
336
- ax.set_ylabel('Percentage (%)')
337
- ax.set_title('Student Attendance and Engagement Metrics')
338
- ax.legend()
339
- plt.xticks(rotation=45)
340
-
341
- st.pyplot(fig)
342
-
343
- return fig
344
-
345
- def download_chart(fig, filename):
346
- # Create a buffer to hold the image data
347
- buffer = io.BytesIO()
348
- # Save the figure to the buffer
349
- fig.savefig(buffer, format='png')
350
- # Set the file pointer to the beginning
351
- buffer.seek(0)
352
- # Add a download button to Streamlit
353
- st.download_button(label="Download Chart", data=buffer, file_name=filename, mime='image/png')
354
-
355
- def download_llm_output(content, filename):
356
- # Create a buffer to hold the text data
357
- buffer = io.BytesIO()
358
- buffer.write(content.encode('utf-8'))
359
- buffer.seek(0)
360
- # Add a download button to Streamlit
361
- st.download_button(label="Download LLM Output", data=buffer, file_name=filename, mime='text/plain')
362
-
363
- def prepare_llm_input(student_metrics_df):
364
- # Convert the student metrics DataFrame to a string
365
- metrics_str = student_metrics_df.to_string(index=False)
366
- llm_input = f"""
367
- Based on the following student metrics:
368
-
369
- {metrics_str}
370
-
371
- Provide:
372
-
373
- 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.
374
-
375
- 2. Recommendations and Next Steps: Provide interpretations based on the analysis and suggest possible next steps or strategies to improve student outcomes.
376
- """
377
- return llm_input
378
-
379
- def prompt_response_from_hf_llm(llm_input):
380
- # Generate the refined prompt using Hugging Face API
381
- response = client.chat.completions.create(
382
- model="meta-llama/Llama-3.1-70B-Instruct",
383
- messages=[
384
- {"role": "user", "content": llm_input}
385
- ],
386
- stream=True,
387
- temperature=0.5,
388
- max_tokens=1024,
389
- top_p=0.7
390
- )
391
-
392
- # Combine messages if response is streamed
393
- response_content = ""
394
- for message in response:
395
- response_content += message.choices[0].delta.content
396
-
397
- return response_content.strip()
398
-
399
- if __name__ == '__main__':
400
- main()