Repository navigation
Expand file tree
/
Copy pathIEP_WordDocxGeneration.py
More file actions
240 lines (203 loc) · 9.22 KB
/
Copy pathIEP_WordDocxGeneration.py
File metadata and controls
240 lines (203 loc) · 9.22 KB
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
import os, sys, shlex, subprocess, gam, datetime, json, smtplib, logging, re
from pathlib import Path
import pandas as pd
from sqlalchemy import create_engine, URL
import docx
from docx import Document
from docx.oxml.shared import OxmlElement
from docx.oxml.ns import qn
import glob
from timeit import default_timer as timer
from email.message import EmailMessage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from logging.handlers import SysLogHandler
"""
IEP Word Docx generator with GAM Integration
2026
"""
# Helper function to create actual clickable hyperlinks in python-docx
def add_hyperlink(paragraph, text, url):
part = paragraph.part
r_id = part.relate_to(url, docx.opc.constants.RELATIONSHIP_TYPE.HYPERLINK, is_external=True)
hyperlink = OxmlElement('w:hyperlink')
hyperlink.set(qn('r:id'), r_id)
new_run = OxmlElement('w:r')
rPr = OxmlElement('w:rPr')
c = OxmlElement('w:color')
c.set(qn('w:val'), '0563C1')
rPr.append(c)
u = OxmlElement('w:u')
u.set(qn('w:val'), 'single')
rPr.append(u)
new_run.append(rPr)
t = OxmlElement('w:t')
t.text = text
new_run.append(t)
hyperlink.append(new_run)
paragraph._p.append(hyperlink)
return hyperlink
# Setup basic logging to match your environment
logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')
logger = logging.getLogger(__name__)
# 1. Load Configurations
confighome = Path.home() / ".Acalanes" / "Acalanes.json"
with open(confighome) as f:
configs = json.load(f)
logger = logging.getLogger('IEP Word Docx Generation')
logger.setLevel(logging.INFO)
console_handler = logging.StreamHandler()
syslog_handler = logging.handlers.SysLogHandler(address = (configs['logserveraddress'],514))
formatter = logging.Formatter('%(name)s: %(levelname)s - %(message)s')
console_handler.setFormatter(formatter)
syslog_handler.setFormatter(formatter)
logger.addHandler(syslog_handler)
logger.addHandler(console_handler)
# 2. Setup SQLAlchemy Engine
connection_string = (
"DRIVER={SQL Server};"
"SERVER=" + configs['LocalAERIES_Server'] + ";"
"DATABASE=" + configs['LocalAUHSD'] + ";"
"UID=" + configs['LocalAERIES_Username'] + ";"
"PWD=" + configs['LocalAERIES_Password'] + ";"
)
connection_url = URL.create("mssql+pyodbc", query={"odbc_connect": connection_string})
engine = create_engine(connection_url)
# 3. Master SQL Query (Added Teacher_Email)
QueryStr = """
SELECT
r.Teacher_FN,
r.Teacher_LN,
r.Teacher_Email,
r.Semester,
r.CourseNumber,
r.CourseName,
r.SectionNumber,
r.STU_ID,
r.Student_FN,
r.Student_LN,
r.IEPLink,
r.CaseManager_FN,
r.CaseManager_LN,
r.CaseManager_Email,
n.NoteContent,
n.DateAdded,
author.FN AS NoteAuthor_FN,
author.LN AS NoteAuthor_LN
FROM
vw_IEP_TeacherRoster r
LEFT JOIN
IEPNotes n ON r.STU_ID = n.STU_ID AND n.IsDeleted = 0
LEFT JOIN
STF author ON n.Author_HRID = author.ID
ORDER BY
r.Teacher_LN, r.Semester, r.CourseName, r.SectionNumber, r.Student_LN, n.DateAdded DESC;
"""
os.chdir(configs['PythonTempDirectory'])
output_dir = "C:\\Users\\Public\\PythonTemp"
# 4. Fetch Data using Pandas
with engine.begin() as connection:
logger.info('Connecting to database to get IEP rosters')
df = pd.read_sql_query(QueryStr, connection)
logger.info('Closed database connection')
# 5. Clean and Group Data
logger.info("Processing data for Word documents")
# Added Teacher_Email to cleanup
text_cols = [
'Teacher_FN', 'Teacher_LN', 'Teacher_Email', 'Student_FN', 'Student_LN',
'CaseManager_FN', 'CaseManager_LN', 'CaseManager_Email', 'NoteAuthor_FN', 'NoteAuthor_LN',
'IEPLink', 'NoteContent', 'CourseNumber', 'CourseName', 'SectionNumber', 'Semester'
]
for col in text_cols:
df[col] = df[col].fillna('').astype(str).replace(['nan', 'None', '<NA>'], '')
df['TeacherName'] = (df['Teacher_FN'] + ' ' + df['Teacher_LN']).str.strip()
df['StudentName'] = (df['Student_FN'] + ' ' + df['Student_LN']).str.strip()
df['CaseManagerName'] = (df['CaseManager_FN'] + ' ' + df['CaseManager_LN']).str.strip()
df['NoteAuthorName'] = (df['NoteAuthor_FN'] + ' ' + df['NoteAuthor_LN']).str.strip()
teachers = [t for t in df['TeacherName'].unique() if str(t).strip() not in ('', 'nan', 'None')]
# Get GAM configs (Fallback to placeholders if not in JSON yet)
gam_admin_user = configs.get('GAMAdminUser', 'edannewitz@auhsdschools.org')
gdrive_folder_id = configs.get('GDriveFolderID', '0AHDs-9Iq6iXMUk9PVA')
# 6. Generate the Word Documents & Upload via GAM
for teacher in teachers:
teacher_str = str(teacher)
teacher_df = df[df['TeacherName'] == teacher]
# Extract the teacher's email for sharing later
teacher_email = teacher_df.iloc[0]['Teacher_Email']
doc = Document()
doc.add_heading(f"IEP Snapshot: {teacher_str}", 0)
classes = teacher_df[['Semester', 'CourseName', 'CourseNumber', 'SectionNumber']].drop_duplicates().values
for semester, course_name, course_num, sec_num in classes:
class_df = teacher_df[
(teacher_df['Semester'] == semester) &
(teacher_df['CourseName'] == course_name) &
(teacher_df['CourseNumber'] == course_num) &
(teacher_df['SectionNumber'] == sec_num)
]
term_str = f"Term: {semester} | " if semester else ""
c_name = course_name if course_name else "Unknown Course"
doc.add_heading(f"{term_str}{c_name} ({course_num}) - Section {sec_num}", level=1)
students = class_df['STU_ID'].unique()
for stu_id in students:
stu_df = class_df[class_df['STU_ID'] == stu_id]
stu_info = stu_df.iloc[0]
p = doc.add_paragraph()
p.add_run(f"Student: {stu_info['StudentName']} (ID: {stu_id})\n").bold = True
p.add_run("Case Manager: ")
case_manager_name = stu_info['CaseManagerName']
if case_manager_name:
if stu_info['CaseManager_Email']:
mailto_link = f"mailto:{stu_info['CaseManager_Email']}"
add_hyperlink(p, case_manager_name, mailto_link)
else:
p.add_run(case_manager_name)
else:
p.add_run("Unassigned")
p.add_run("\n")
p.add_run("IEP Link: ")
if stu_info['IEPLink']:
add_hyperlink(p, "View IEP Document", stu_info['IEPLink'])
else:
p.add_run("No link provided")
notes_df = stu_df[stu_df['NoteContent'] != '']
if not notes_df.empty:
doc.add_paragraph("Team Notes:", style='List Bullet')
for _, note_row in notes_df.iterrows():
date_val = note_row['DateAdded']
if pd.isna(date_val) or date_val == '':
date_str = "Unknown Date"
else:
date_str = pd.to_datetime(date_val).strftime('%m/%d/%Y')
note_text = f"[{date_str}] {note_row['NoteAuthorName']}: {note_row['NoteContent']}"
note_p = doc.add_paragraph(note_text)
note_p.paragraph_format.left_indent = 360000
# Save locally
safe_filename = teacher_str.replace(" ", "_").replace("/", "-")
local_path = os.path.join(output_dir, f"{safe_filename}_IEP_Roster.docx")
doc.save(local_path)
logger.info(f"Saved locally: {local_path}")
# --- GAM Integration: Upload and Share ---
if teacher_email and '@' in teacher_email:
try:
logger.info(f"Uploading {safe_filename} to Google Drive...")
# Use shlex.split to handle spaces in the file path safely
upload_cmd = f'gam user {gam_admin_user} add drivefile localfile "{local_path}" parentid "{gdrive_folder_id}"'
upload_process = subprocess.run(shlex.split(upload_cmd), capture_output=True, text=True)
# Use regex to hunt down the new Google Drive File ID in GAM's output
match = re.search(r'id:\s*([a-zA-Z0-9_-]+)', upload_process.stdout)
if match:
file_id = match.group(1)
logger.info(f"Upload successful! File ID: {file_id}")
# Share the file with the teacher as a reader
share_cmd = f'gam user {gam_admin_user} add drivefileacl {file_id} user {teacher_email} role reader'
logger.info(f"Setting sharing permissions for {teacher_email}...")
subprocess.run(shlex.split(share_cmd), capture_output=True, text=True)
logger.info(f"Successfully secured and shared doc with {teacher_email}")
else:
logger.error(f"Upload failed or couldn't parse File ID. GAM Output: {upload_process.stdout} | {upload_process.stderr}")
except Exception as e:
logger.error(f"GAM execution failed for {teacher_str}: {e}")
else:
logger.warning(f"No valid email found for {teacher_str}. File was saved locally but not uploaded/shared.")
logger.info("All IEP Roster documents generated and processed successfully!")