Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -14,7 +14,10 @@ import gradio as gr
|
|
| 14 |
import pdfplumber
|
| 15 |
import requests
|
| 16 |
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
| 18 |
from google.oauth2.credentials import Credentials
|
| 19 |
from googleapiclient.discovery import build
|
| 20 |
from googleapiclient.errors import HttpError
|
|
@@ -25,18 +28,15 @@ logger = logging.getLogger("proplanner")
|
|
| 25 |
# -------------------------
|
| 26 |
# Config / Secrets (set in HF Secrets)
|
| 27 |
# -------------------------
|
| 28 |
-
# OAuth client id (Web app)
|
| 29 |
CLIENT_ID = os.environ.get("GoogleClientID")
|
| 30 |
CLIENT_SECRET = os.environ.get("GoogleClientSecret")
|
| 31 |
-
|
| 32 |
-
REDIRECT_URI = os.environ.get("REDIRECT_URI")
|
| 33 |
|
| 34 |
SCOPES = ["https://www.googleapis.com/auth/calendar"]
|
| 35 |
TIMEZONE = "America/New_York"
|
| 36 |
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
|
| 41 |
# -------------------------
|
| 42 |
# Utility helpers
|
|
@@ -45,16 +45,19 @@ def build_auth_url():
|
|
| 45 |
"""
|
| 46 |
Build the Google authorization URL. User will be redirected here to consent.
|
| 47 |
"""
|
|
|
|
|
|
|
|
|
|
| 48 |
base = "https://accounts.google.com/o/oauth2/v2/auth"
|
| 49 |
params = {
|
| 50 |
"client_id": CLIENT_ID,
|
| 51 |
"response_type": "code",
|
| 52 |
"scope": " ".join(SCOPES + ["openid", "email", "profile"]),
|
| 53 |
"redirect_uri": REDIRECT_URI,
|
| 54 |
-
"access_type": "offline",
|
| 55 |
-
"prompt": "consent"
|
| 56 |
}
|
| 57 |
-
parts = [f"{k}={requests.utils.quote(v, safe='')}" for k, v in params.items()]
|
| 58 |
return base + "?" + "&".join(parts)
|
| 59 |
|
| 60 |
def exchange_code_for_tokens(code: str):
|
|
@@ -74,13 +77,6 @@ def exchange_code_for_tokens(code: str):
|
|
| 74 |
resp.raise_for_status()
|
| 75 |
return resp.json()
|
| 76 |
|
| 77 |
-
def refresh_tokens_if_needed(creds: Credentials):
|
| 78 |
-
"""
|
| 79 |
-
Ensure Credentials are valid (google lib handles refresh automatically if refresh_token present).
|
| 80 |
-
"""
|
| 81 |
-
# google-> Credentials.refresh requires a Request object; google-auth-requests will handle if needed when making API calls.
|
| 82 |
-
return creds
|
| 83 |
-
|
| 84 |
def creds_from_token_info(token_info: dict):
|
| 85 |
"""
|
| 86 |
Construct google.oauth2.credentials.Credentials from token response.
|
|
@@ -104,7 +100,9 @@ def get_user_email_from_id_token(id_token: str):
|
|
| 104 |
parts = id_token.split(".")
|
| 105 |
if len(parts) < 2:
|
| 106 |
return None
|
| 107 |
-
payload = parts[1]
|
|
|
|
|
|
|
| 108 |
decoded = base64.urlsafe_b64decode(payload.encode("utf-8"))
|
| 109 |
info = json.loads(decoded)
|
| 110 |
return info.get("email")
|
|
@@ -123,25 +121,19 @@ def build_calendar_service(creds: Credentials):
|
|
| 123 |
raise
|
| 124 |
|
| 125 |
# -------------------------
|
| 126 |
-
# Google Calendar
|
| 127 |
# -------------------------
|
| 128 |
def create_single_assignment_event(service, calendar_id, summary, iso_datetime, duration_minutes=60, timezone=TIMEZONE):
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
If iso_datetime lacks timezone offset, Google will treat it relative to provided timeZone field.
|
| 132 |
-
We set end time = start + duration_minutes.
|
| 133 |
-
"""
|
| 134 |
-
# Try parsing; if contains 'T' and timezone or offset present, use as-is. Otherwise construct start/end.
|
| 135 |
if "T" in iso_datetime:
|
| 136 |
try:
|
| 137 |
-
# if iso contains timezone offset (e.g., -05:00) we can use it directly
|
| 138 |
start_str = iso_datetime
|
| 139 |
-
# compute end by parsing and adding duration (attempt various parse formats)
|
| 140 |
try:
|
| 141 |
dt = datetime.fromisoformat(iso_datetime)
|
| 142 |
except Exception:
|
| 143 |
-
#
|
| 144 |
-
dt = datetime.fromisoformat(
|
| 145 |
end_dt = dt + timedelta(minutes=duration_minutes)
|
| 146 |
end_str = end_dt.isoformat()
|
| 147 |
event = {
|
|
@@ -154,7 +146,7 @@ def create_single_assignment_event(service, calendar_id, summary, iso_datetime,
|
|
| 154 |
except Exception as e:
|
| 155 |
logger.warning("Could not parse ISO datetime; falling back to date-only event: %s", e)
|
| 156 |
|
| 157 |
-
#
|
| 158 |
try:
|
| 159 |
date_part = iso_datetime.split("T")[0] if "T" in iso_datetime else iso_datetime
|
| 160 |
event = {
|
|
@@ -169,15 +161,9 @@ def create_single_assignment_event(service, calendar_id, summary, iso_datetime,
|
|
| 169 |
raise
|
| 170 |
|
| 171 |
def create_class_recurring_event(service, calendar_id, summary, location, start_date, end_date, start_time, end_time, weekdays, timezone=TIMEZONE):
|
| 172 |
-
"""
|
| 173 |
-
Create a recurring weekly event using RRULE.
|
| 174 |
-
weekdays should be like "Mon,Wed" or "Tue,Thu".
|
| 175 |
-
start_time/end_time in "HH:MM" 24h format.
|
| 176 |
-
"""
|
| 177 |
byday_map = {"Mon":"MO","Tue":"TU","Wed":"WE","Thu":"TH","Fri":"FR","Sat":"SA","Sun":"SU"}
|
| 178 |
-
# Map to RRULE BYDAY
|
| 179 |
byday_list = []
|
| 180 |
-
for d in weekdays.split(","):
|
| 181 |
key = d.strip()
|
| 182 |
if key in byday_map:
|
| 183 |
byday_list.append(byday_map[key])
|
|
@@ -201,16 +187,12 @@ def create_class_recurring_event(service, calendar_id, summary, location, start_
|
|
| 201 |
return created.get("htmlLink")
|
| 202 |
|
| 203 |
# -------------------------
|
| 204 |
-
# CSV readers
|
| 205 |
# -------------------------
|
| 206 |
def df_from_assignments_state(assignments_state):
|
| 207 |
-
"""
|
| 208 |
-
assignments_state is a DataFrame or None; we expect columns: name, due_datetime (ISO)
|
| 209 |
-
"""
|
| 210 |
if assignments_state is None:
|
| 211 |
return None
|
| 212 |
if isinstance(assignments_state, str):
|
| 213 |
-
# if a path
|
| 214 |
try:
|
| 215 |
return pd.read_csv(assignments_state)
|
| 216 |
except Exception:
|
|
@@ -220,9 +202,6 @@ def df_from_assignments_state(assignments_state):
|
|
| 220 |
return None
|
| 221 |
|
| 222 |
def df_from_classes_state(classes_state):
|
| 223 |
-
"""
|
| 224 |
-
classes_state is DataFrame expected to have: name, location, start_time, end_time, weekdays, start_date, end_date
|
| 225 |
-
"""
|
| 226 |
if classes_state is None:
|
| 227 |
return None
|
| 228 |
if isinstance(classes_state, str):
|
|
@@ -235,21 +214,15 @@ def df_from_classes_state(classes_state):
|
|
| 235 |
return None
|
| 236 |
|
| 237 |
# -------------------------
|
| 238 |
-
# Sending functions
|
| 239 |
# -------------------------
|
| 240 |
def send_assignments_df_to_calendar(assignments_df, creds_info, calendar_name="ProPlanner Calendar"):
|
| 241 |
-
"""
|
| 242 |
-
assignments_df expected columns: name, due_datetime (ISO string)
|
| 243 |
-
creds_info: token dict as returned by exchange_code_for_tokens or saved tokens
|
| 244 |
-
Returns (success_count, failures, message)
|
| 245 |
-
"""
|
| 246 |
if assignments_df is None or assignments_df.empty:
|
| 247 |
return 0, ["No assignments provided"], "No assignments to send."
|
| 248 |
|
| 249 |
creds = creds_from_token_info(creds_info)
|
| 250 |
service = build_calendar_service(creds)
|
| 251 |
|
| 252 |
-
# Create a new calendar for this app (optional) and get calendarId
|
| 253 |
calendar = {"summary": calendar_name, "timeZone": TIMEZONE}
|
| 254 |
created_cal = service.calendars().insert(body=calendar).execute()
|
| 255 |
cal_id = created_cal["id"]
|
|
@@ -275,9 +248,6 @@ def send_assignments_df_to_calendar(assignments_df, creds_info, calendar_name="P
|
|
| 275 |
return success, failures, f"Created {success} assignment events (calendar: {calendar_name})."
|
| 276 |
|
| 277 |
def send_classes_df_to_calendar(classes_df, creds_info, calendar_name="ProPlanner Calendar"):
|
| 278 |
-
"""
|
| 279 |
-
classes_df expected: name, location, start_time (HH:MM), end_time (HH:MM), weekdays (Mon,Tue...), start_date, end_date
|
| 280 |
-
"""
|
| 281 |
if classes_df is None or classes_df.empty:
|
| 282 |
return 0, ["No classes provided"], "No classes to send."
|
| 283 |
|
|
@@ -316,92 +286,113 @@ def send_classes_df_to_calendar(classes_df, creds_info, calendar_name="ProPlanne
|
|
| 316 |
return success, failures, f"Created {success} class recurring events (calendar: {calendar_name})."
|
| 317 |
|
| 318 |
# -------------------------
|
| 319 |
-
#
|
| 320 |
# -------------------------
|
| 321 |
-
# For brevity: we will call your existing extract_dates(pdf_file) if present;
|
| 322 |
-
# otherwise include a very small fallback extractor that returns empty dataframes.
|
| 323 |
try:
|
| 324 |
-
# If you defined extract_dates earlier in this repo, import it. Otherwise, assume it's in the same file.
|
| 325 |
from extract_main import extract_dates as external_extract_dates # optional
|
| 326 |
def run_extraction(pdf_path):
|
| 327 |
return external_extract_dates(pdf_path)
|
| 328 |
except Exception:
|
| 329 |
-
# fallback: minimal extractor that uses regex functions to produce DataFrames
|
| 330 |
def run_extraction(pdf_path):
|
| 331 |
-
# Simple fallback: scan pdf and return two small dataframes with no events
|
| 332 |
try:
|
| 333 |
with pdfplumber.open(pdf_path) as pdf:
|
| 334 |
text = "\n".join(page.extract_text() or "" for page in pdf.pages)
|
| 335 |
except Exception as e:
|
| 336 |
return None, None, f"Error reading PDF: {e}"
|
| 337 |
-
# Use very small regex to find dates β this is a fallback; your main extractor should replace this.
|
| 338 |
return None, None, "No extraction available in this deployment. Please upload CSVs or wire your extractor."
|
| 339 |
|
| 340 |
# -------------------------
|
| 341 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 342 |
# -------------------------
|
| 343 |
def start_google_oauth():
|
| 344 |
"""
|
| 345 |
-
|
| 346 |
"""
|
| 347 |
-
if not CLIENT_ID or not CLIENT_SECRET:
|
| 348 |
-
return "ERROR: CLIENT_ID/CLIENT_SECRET not set in environment.", ""
|
| 349 |
url = build_auth_url()
|
| 350 |
-
|
|
|
|
|
|
|
| 351 |
|
| 352 |
def finish_google_oauth(code_text):
|
| 353 |
"""
|
| 354 |
-
|
|
|
|
| 355 |
"""
|
| 356 |
try:
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 365 |
token_info = exchange_code_for_tokens(code)
|
| 366 |
-
# decode id_token for email if present
|
| 367 |
user_email = None
|
| 368 |
if "id_token" in token_info:
|
| 369 |
user_email = get_user_email_from_id_token(token_info["id_token"])
|
| 370 |
-
|
| 371 |
-
|
|
|
|
| 372 |
except Exception as e:
|
| 373 |
logger.error("OAuth finish error: %s", e)
|
| 374 |
-
|
|
|
|
| 375 |
|
| 376 |
def handle_extract(pdf_file):
|
| 377 |
-
"""
|
| 378 |
-
Called when user uploads PDF and clicks Extract.
|
| 379 |
-
Returns: assignments_df (preview CSV path), classes_df (preview CSV path), message, and also store DataFrames in state via return.
|
| 380 |
-
We'll return file paths for download components and DataFrames for state.
|
| 381 |
-
"""
|
| 382 |
if pdf_file is None:
|
| 383 |
return None, None, "No PDF uploaded."
|
| 384 |
schedule_path, deadlines_path, message = run_extraction(pdf_file.name)
|
| 385 |
-
# run_extraction should return two temp file paths OR (None, None, message)
|
| 386 |
assignments_df = None
|
| 387 |
classes_df = None
|
| 388 |
if schedule_path and os.path.exists(schedule_path):
|
| 389 |
classes_df = pd.read_csv(schedule_path)
|
| 390 |
if deadlines_path and os.path.exists(deadlines_path):
|
| 391 |
assignments_df = pd.read_csv(deadlines_path)
|
| 392 |
-
# If the extractor returned DataFrames directly, handle that (some implementations do)
|
| 393 |
if isinstance(schedule_path, pd.DataFrame):
|
| 394 |
classes_df = schedule_path
|
| 395 |
if isinstance(deadlines_path, pd.DataFrame):
|
| 396 |
assignments_df = deadlines_path
|
| 397 |
-
|
| 398 |
message_out = message or "Extraction complete."
|
| 399 |
return assignments_df, classes_df, message_out
|
| 400 |
|
| 401 |
def upload_csv_to_df(file):
|
| 402 |
-
"""
|
| 403 |
-
Gradio file upload to DataFrame
|
| 404 |
-
"""
|
| 405 |
if file is None:
|
| 406 |
return None, "No file uploaded."
|
| 407 |
try:
|
|
@@ -412,9 +403,6 @@ def upload_csv_to_df(file):
|
|
| 412 |
return None, f"Failed to read CSV: {e}"
|
| 413 |
|
| 414 |
def send_extracted_assignments_to_calendar(assignments_state, token_state):
|
| 415 |
-
"""
|
| 416 |
-
Method 1: send extracted assignments stored in assignments_state to Google Calendar using token_state.
|
| 417 |
-
"""
|
| 418 |
if token_state is None:
|
| 419 |
return "ERROR: Not authenticated. Please sign in and finish login."
|
| 420 |
assignments_df = df_from_assignments_state(assignments_state)
|
|
@@ -474,20 +462,17 @@ with gr.Blocks(theme=gr.themes.Soft(), title="π ProPlanner") as demo:
|
|
| 474 |
pdf_input = gr.File(label="π Upload Syllabus PDF (.pdf)")
|
| 475 |
extract_btn = gr.Button("π Extract (Method 1)", variant="primary")
|
| 476 |
extract_status = gr.Textbox(label="Extraction status", interactive=False, value="Ready")
|
| 477 |
-
# States that hold DataFrames (Method 1)
|
| 478 |
assignments_state = gr.State(None)
|
| 479 |
classes_state = gr.State(None)
|
| 480 |
|
| 481 |
with gr.Column():
|
| 482 |
-
# OAuth controls
|
| 483 |
auth_url_box = gr.Textbox(label="Authorization URL", interactive=False)
|
| 484 |
open_auth_btn = gr.Button("π Sign in with Google (open consent page)")
|
| 485 |
code_input = gr.Textbox(label="Paste the `code` param from the URL after redirect", placeholder="paste code or full URL here")
|
| 486 |
finish_auth_btn = gr.Button("Finish Login (exchange code)")
|
| 487 |
auth_status = gr.Textbox(label="Auth status", interactive=False, value="Not authenticated")
|
| 488 |
-
# Token state
|
| 489 |
token_state = gr.State(None)
|
| 490 |
-
|
| 491 |
gr.Markdown("### Method 3 β Upload your own CSVs (fallback)")
|
| 492 |
with gr.Row():
|
| 493 |
with gr.Column():
|
|
@@ -517,37 +502,36 @@ with gr.Blocks(theme=gr.themes.Soft(), title="π ProPlanner") as demo:
|
|
| 517 |
send_uploaded_classes_status = gr.Textbox(interactive=False, label="Send status", value="")
|
| 518 |
|
| 519 |
# Wire up buttons
|
| 520 |
-
|
|
|
|
| 521 |
finish_auth_btn.click(fn=finish_google_oauth, inputs=[code_input], outputs=[token_state, auth_status])
|
| 522 |
|
| 523 |
-
# Extraction
|
| 524 |
extract_btn.click(fn=handle_extract, inputs=[pdf_input], outputs=[assignments_state, classes_state, extract_status])
|
| 525 |
|
| 526 |
-
# Uploaded CSV loaders
|
| 527 |
upload_assign_btn.click(fn=lambda f: upload_csv_to_df(f), inputs=[upload_assignments], outputs=[assignments_uploaded_state, upload_assign_status])
|
| 528 |
upload_classes_btn.click(fn=lambda f: upload_csv_to_df(f), inputs=[upload_classes], outputs=[classes_uploaded_state, upload_classes_status])
|
| 529 |
|
| 530 |
-
# Previews: show DataFrames if available
|
| 531 |
-
# For previews, we'll pass the DataFrames to the Dataframe components
|
| 532 |
def preview_df(df):
|
| 533 |
if df is None:
|
| 534 |
return pd.DataFrame()
|
| 535 |
return df
|
| 536 |
|
| 537 |
-
|
| 538 |
-
|
| 539 |
-
upload_assign_btn.click(fn=lambda df, : preview_df(df), inputs=[assignments_uploaded_state], outputs=[preview_uploaded_assignments])
|
| 540 |
-
upload_classes_btn.click(fn=lambda df, : preview_df(df), inputs=[classes_uploaded_state], outputs=[preview_uploaded_classes])
|
| 541 |
|
| 542 |
-
# Send actions
|
| 543 |
send_extracted_assignments_btn.click(fn=send_extracted_assignments_to_calendar, inputs=[assignments_state, token_state], outputs=[send_extracted_assignments_status])
|
| 544 |
send_extracted_classes_btn.click(fn=send_extracted_classes_to_calendar, inputs=[classes_state, token_state], outputs=[send_extracted_classes_status])
|
| 545 |
|
| 546 |
send_uploaded_assignments_btn.click(fn=send_uploaded_assignments_to_calendar, inputs=[assignments_uploaded_state, token_state], outputs=[send_uploaded_assignments_status])
|
| 547 |
send_uploaded_classes_btn.click(fn=send_uploaded_classes_to_calendar, inputs=[classes_uploaded_state, token_state], outputs=[send_uploaded_classes_status])
|
| 548 |
|
| 549 |
-
gr.Markdown("### Notes\n- Click **Sign in with Google** then
|
|
|
|
|
|
|
|
|
|
| 550 |
|
| 551 |
-
# Launch
|
| 552 |
if __name__ == "__main__":
|
| 553 |
-
|
|
|
|
|
|
|
|
|
| 14 |
import pdfplumber
|
| 15 |
import requests
|
| 16 |
|
| 17 |
+
from fastapi import FastAPI, Request
|
| 18 |
+
from fastapi.responses import PlainTextResponse, HTMLResponse
|
| 19 |
+
|
| 20 |
+
# Google client libs (ensure these are in requirements.txt)
|
| 21 |
from google.oauth2.credentials import Credentials
|
| 22 |
from googleapiclient.discovery import build
|
| 23 |
from googleapiclient.errors import HttpError
|
|
|
|
| 28 |
# -------------------------
|
| 29 |
# Config / Secrets (set in HF Secrets)
|
| 30 |
# -------------------------
|
|
|
|
| 31 |
CLIENT_ID = os.environ.get("GoogleClientID")
|
| 32 |
CLIENT_SECRET = os.environ.get("GoogleClientSecret")
|
| 33 |
+
REDIRECT_URI = os.environ.get("REDIRECT_URI") # must be like: https://<your-space>.hf.space/callback
|
|
|
|
| 34 |
|
| 35 |
SCOPES = ["https://www.googleapis.com/auth/calendar"]
|
| 36 |
TIMEZONE = "America/New_York"
|
| 37 |
|
| 38 |
+
# Temporary file path to store the most recent OAuth code from the callback
|
| 39 |
+
OAUTH_CODE_FILE = "/tmp/proplanner_oauth_code.txt"
|
|
|
|
| 40 |
|
| 41 |
# -------------------------
|
| 42 |
# Utility helpers
|
|
|
|
| 45 |
"""
|
| 46 |
Build the Google authorization URL. User will be redirected here to consent.
|
| 47 |
"""
|
| 48 |
+
if not CLIENT_ID or not CLIENT_SECRET or not REDIRECT_URI:
|
| 49 |
+
return "ERROR: GoogleClientID/GoogleClientSecret/REDIRECT_URI not set in Space secrets."
|
| 50 |
+
|
| 51 |
base = "https://accounts.google.com/o/oauth2/v2/auth"
|
| 52 |
params = {
|
| 53 |
"client_id": CLIENT_ID,
|
| 54 |
"response_type": "code",
|
| 55 |
"scope": " ".join(SCOPES + ["openid", "email", "profile"]),
|
| 56 |
"redirect_uri": REDIRECT_URI,
|
| 57 |
+
"access_type": "offline", # request refresh token
|
| 58 |
+
"prompt": "consent" # force refresh_token on first consent
|
| 59 |
}
|
| 60 |
+
parts = [f"{k}={requests.utils.quote(str(v), safe='')}" for k, v in params.items()]
|
| 61 |
return base + "?" + "&".join(parts)
|
| 62 |
|
| 63 |
def exchange_code_for_tokens(code: str):
|
|
|
|
| 77 |
resp.raise_for_status()
|
| 78 |
return resp.json()
|
| 79 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
def creds_from_token_info(token_info: dict):
|
| 81 |
"""
|
| 82 |
Construct google.oauth2.credentials.Credentials from token response.
|
|
|
|
| 100 |
parts = id_token.split(".")
|
| 101 |
if len(parts) < 2:
|
| 102 |
return None
|
| 103 |
+
payload = parts[1]
|
| 104 |
+
# Fix padding
|
| 105 |
+
payload += "=" * (-len(payload) % 4)
|
| 106 |
decoded = base64.urlsafe_b64decode(payload.encode("utf-8"))
|
| 107 |
info = json.loads(decoded)
|
| 108 |
return info.get("email")
|
|
|
|
| 121 |
raise
|
| 122 |
|
| 123 |
# -------------------------
|
| 124 |
+
# Google Calendar helpers (same as your functions)
|
| 125 |
# -------------------------
|
| 126 |
def create_single_assignment_event(service, calendar_id, summary, iso_datetime, duration_minutes=60, timezone=TIMEZONE):
|
| 127 |
+
if not iso_datetime:
|
| 128 |
+
raise ValueError("Missing iso_datetime")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
if "T" in iso_datetime:
|
| 130 |
try:
|
|
|
|
| 131 |
start_str = iso_datetime
|
|
|
|
| 132 |
try:
|
| 133 |
dt = datetime.fromisoformat(iso_datetime)
|
| 134 |
except Exception:
|
| 135 |
+
# try removing timezone offset part for parsing
|
| 136 |
+
dt = datetime.fromisoformat(re.split(r"[+-]", iso_datetime)[0])
|
| 137 |
end_dt = dt + timedelta(minutes=duration_minutes)
|
| 138 |
end_str = end_dt.isoformat()
|
| 139 |
event = {
|
|
|
|
| 146 |
except Exception as e:
|
| 147 |
logger.warning("Could not parse ISO datetime; falling back to date-only event: %s", e)
|
| 148 |
|
| 149 |
+
# fallback to all-day event
|
| 150 |
try:
|
| 151 |
date_part = iso_datetime.split("T")[0] if "T" in iso_datetime else iso_datetime
|
| 152 |
event = {
|
|
|
|
| 161 |
raise
|
| 162 |
|
| 163 |
def create_class_recurring_event(service, calendar_id, summary, location, start_date, end_date, start_time, end_time, weekdays, timezone=TIMEZONE):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
byday_map = {"Mon":"MO","Tue":"TU","Wed":"WE","Thu":"TH","Fri":"FR","Sat":"SA","Sun":"SU"}
|
|
|
|
| 165 |
byday_list = []
|
| 166 |
+
for d in str(weekdays).split(","):
|
| 167 |
key = d.strip()
|
| 168 |
if key in byday_map:
|
| 169 |
byday_list.append(byday_map[key])
|
|
|
|
| 187 |
return created.get("htmlLink")
|
| 188 |
|
| 189 |
# -------------------------
|
| 190 |
+
# CSV readers
|
| 191 |
# -------------------------
|
| 192 |
def df_from_assignments_state(assignments_state):
|
|
|
|
|
|
|
|
|
|
| 193 |
if assignments_state is None:
|
| 194 |
return None
|
| 195 |
if isinstance(assignments_state, str):
|
|
|
|
| 196 |
try:
|
| 197 |
return pd.read_csv(assignments_state)
|
| 198 |
except Exception:
|
|
|
|
| 202 |
return None
|
| 203 |
|
| 204 |
def df_from_classes_state(classes_state):
|
|
|
|
|
|
|
|
|
|
| 205 |
if classes_state is None:
|
| 206 |
return None
|
| 207 |
if isinstance(classes_state, str):
|
|
|
|
| 214 |
return None
|
| 215 |
|
| 216 |
# -------------------------
|
| 217 |
+
# Sending functions
|
| 218 |
# -------------------------
|
| 219 |
def send_assignments_df_to_calendar(assignments_df, creds_info, calendar_name="ProPlanner Calendar"):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 220 |
if assignments_df is None or assignments_df.empty:
|
| 221 |
return 0, ["No assignments provided"], "No assignments to send."
|
| 222 |
|
| 223 |
creds = creds_from_token_info(creds_info)
|
| 224 |
service = build_calendar_service(creds)
|
| 225 |
|
|
|
|
| 226 |
calendar = {"summary": calendar_name, "timeZone": TIMEZONE}
|
| 227 |
created_cal = service.calendars().insert(body=calendar).execute()
|
| 228 |
cal_id = created_cal["id"]
|
|
|
|
| 248 |
return success, failures, f"Created {success} assignment events (calendar: {calendar_name})."
|
| 249 |
|
| 250 |
def send_classes_df_to_calendar(classes_df, creds_info, calendar_name="ProPlanner Calendar"):
|
|
|
|
|
|
|
|
|
|
| 251 |
if classes_df is None or classes_df.empty:
|
| 252 |
return 0, ["No classes provided"], "No classes to send."
|
| 253 |
|
|
|
|
| 286 |
return success, failures, f"Created {success} class recurring events (calendar: {calendar_name})."
|
| 287 |
|
| 288 |
# -------------------------
|
| 289 |
+
# Integration with your extractor
|
| 290 |
# -------------------------
|
|
|
|
|
|
|
| 291 |
try:
|
|
|
|
| 292 |
from extract_main import extract_dates as external_extract_dates # optional
|
| 293 |
def run_extraction(pdf_path):
|
| 294 |
return external_extract_dates(pdf_path)
|
| 295 |
except Exception:
|
|
|
|
| 296 |
def run_extraction(pdf_path):
|
|
|
|
| 297 |
try:
|
| 298 |
with pdfplumber.open(pdf_path) as pdf:
|
| 299 |
text = "\n".join(page.extract_text() or "" for page in pdf.pages)
|
| 300 |
except Exception as e:
|
| 301 |
return None, None, f"Error reading PDF: {e}"
|
|
|
|
| 302 |
return None, None, "No extraction available in this deployment. Please upload CSVs or wire your extractor."
|
| 303 |
|
| 304 |
# -------------------------
|
| 305 |
+
# FastAPI app + callback endpoint
|
| 306 |
+
# -------------------------
|
| 307 |
+
app = FastAPI(title="ProPlanner backend")
|
| 308 |
+
|
| 309 |
+
@app.get("/callback")
|
| 310 |
+
async def google_callback(request: Request):
|
| 311 |
+
"""
|
| 312 |
+
Google will redirect users here after consent: /callback?code=...
|
| 313 |
+
We save the code to a temp file so the Gradio UI (running in same process) can pick it up if user clicks Finish Login.
|
| 314 |
+
"""
|
| 315 |
+
params = dict(request.query_params)
|
| 316 |
+
if "error" in params:
|
| 317 |
+
return PlainTextResponse(f"Google OAuth Error: {params.get('error')}")
|
| 318 |
+
code = params.get("code")
|
| 319 |
+
if not code:
|
| 320 |
+
return PlainTextResponse("Missing authorization code in query parameters.")
|
| 321 |
+
try:
|
| 322 |
+
with open(OAUTH_CODE_FILE, "w") as f:
|
| 323 |
+
f.write(code)
|
| 324 |
+
except Exception as e:
|
| 325 |
+
logger.error("Failed to write oauth code file: %s", e)
|
| 326 |
+
return PlainTextResponse("Auth succeeded but server failed to save the code. Check logs.")
|
| 327 |
+
# Friendly HTML response shown in browser after redirect
|
| 328 |
+
html = "<html><body><h2>Authentication successful</h2><p>You can now return to the ProPlanner app and click <strong>Finish Login</strong>. The authorization code has been saved.</p></body></html>"
|
| 329 |
+
return HTMLResponse(content=html, status_code=200)
|
| 330 |
+
|
| 331 |
+
# -------------------------
|
| 332 |
+
# Gradio UI & callbacks
|
| 333 |
# -------------------------
|
| 334 |
def start_google_oauth():
|
| 335 |
"""
|
| 336 |
+
Called when user clicks Sign in. Returns URL and a short message.
|
| 337 |
"""
|
|
|
|
|
|
|
| 338 |
url = build_auth_url()
|
| 339 |
+
if url.startswith("ERROR"):
|
| 340 |
+
return url, "Missing Google secrets in Space settings."
|
| 341 |
+
return url, "Opened authorization URL. If your browser blocked a popup, copy the URL above into a new tab."
|
| 342 |
|
| 343 |
def finish_google_oauth(code_text):
|
| 344 |
"""
|
| 345 |
+
Accepts either a pasted code/URL OR will read the code saved by /callback.
|
| 346 |
+
Returns token_info dict and status message.
|
| 347 |
"""
|
| 348 |
try:
|
| 349 |
+
# prefer pasted code if provided
|
| 350 |
+
code = None
|
| 351 |
+
if code_text:
|
| 352 |
+
m = re.search(r"(\?|&)code=([^&]+)", code_text)
|
| 353 |
+
if m:
|
| 354 |
+
code = m.group(2)
|
| 355 |
+
else:
|
| 356 |
+
code = code_text.strip()
|
| 357 |
+
|
| 358 |
+
# fallback: check callback-saved file
|
| 359 |
+
if not code and os.path.exists(OAUTH_CODE_FILE):
|
| 360 |
+
with open(OAUTH_CODE_FILE) as f:
|
| 361 |
+
code = f.read().strip()
|
| 362 |
+
|
| 363 |
+
if not code:
|
| 364 |
+
return None, "No authorization code found. Paste the code or use the callback flow."
|
| 365 |
+
|
| 366 |
token_info = exchange_code_for_tokens(code)
|
|
|
|
| 367 |
user_email = None
|
| 368 |
if "id_token" in token_info:
|
| 369 |
user_email = get_user_email_from_id_token(token_info["id_token"])
|
| 370 |
+
msg = f"Tokens obtained for {user_email or 'unknown user'}. You may now send events to the calendar."
|
| 371 |
+
# Return token_info (stored in gr.State) and a user-friendly message
|
| 372 |
+
return token_info, msg
|
| 373 |
except Exception as e:
|
| 374 |
logger.error("OAuth finish error: %s", e)
|
| 375 |
+
tb = traceback.format_exc()
|
| 376 |
+
return None, f"Failed to exchange code: {e}\n{tb}"
|
| 377 |
|
| 378 |
def handle_extract(pdf_file):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 379 |
if pdf_file is None:
|
| 380 |
return None, None, "No PDF uploaded."
|
| 381 |
schedule_path, deadlines_path, message = run_extraction(pdf_file.name)
|
|
|
|
| 382 |
assignments_df = None
|
| 383 |
classes_df = None
|
| 384 |
if schedule_path and os.path.exists(schedule_path):
|
| 385 |
classes_df = pd.read_csv(schedule_path)
|
| 386 |
if deadlines_path and os.path.exists(deadlines_path):
|
| 387 |
assignments_df = pd.read_csv(deadlines_path)
|
|
|
|
| 388 |
if isinstance(schedule_path, pd.DataFrame):
|
| 389 |
classes_df = schedule_path
|
| 390 |
if isinstance(deadlines_path, pd.DataFrame):
|
| 391 |
assignments_df = deadlines_path
|
|
|
|
| 392 |
message_out = message or "Extraction complete."
|
| 393 |
return assignments_df, classes_df, message_out
|
| 394 |
|
| 395 |
def upload_csv_to_df(file):
|
|
|
|
|
|
|
|
|
|
| 396 |
if file is None:
|
| 397 |
return None, "No file uploaded."
|
| 398 |
try:
|
|
|
|
| 403 |
return None, f"Failed to read CSV: {e}"
|
| 404 |
|
| 405 |
def send_extracted_assignments_to_calendar(assignments_state, token_state):
|
|
|
|
|
|
|
|
|
|
| 406 |
if token_state is None:
|
| 407 |
return "ERROR: Not authenticated. Please sign in and finish login."
|
| 408 |
assignments_df = df_from_assignments_state(assignments_state)
|
|
|
|
| 462 |
pdf_input = gr.File(label="π Upload Syllabus PDF (.pdf)")
|
| 463 |
extract_btn = gr.Button("π Extract (Method 1)", variant="primary")
|
| 464 |
extract_status = gr.Textbox(label="Extraction status", interactive=False, value="Ready")
|
|
|
|
| 465 |
assignments_state = gr.State(None)
|
| 466 |
classes_state = gr.State(None)
|
| 467 |
|
| 468 |
with gr.Column():
|
|
|
|
| 469 |
auth_url_box = gr.Textbox(label="Authorization URL", interactive=False)
|
| 470 |
open_auth_btn = gr.Button("π Sign in with Google (open consent page)")
|
| 471 |
code_input = gr.Textbox(label="Paste the `code` param from the URL after redirect", placeholder="paste code or full URL here")
|
| 472 |
finish_auth_btn = gr.Button("Finish Login (exchange code)")
|
| 473 |
auth_status = gr.Textbox(label="Auth status", interactive=False, value="Not authenticated")
|
|
|
|
| 474 |
token_state = gr.State(None)
|
| 475 |
+
|
| 476 |
gr.Markdown("### Method 3 β Upload your own CSVs (fallback)")
|
| 477 |
with gr.Row():
|
| 478 |
with gr.Column():
|
|
|
|
| 502 |
send_uploaded_classes_status = gr.Textbox(interactive=False, label="Send status", value="")
|
| 503 |
|
| 504 |
# Wire up buttons
|
| 505 |
+
# 1) Clicking Sign-in shows the auth URL in the textbox AND attempts to open it in a new tab.
|
| 506 |
+
open_auth_btn.click(fn=start_google_oauth, inputs=None, outputs=[auth_url_box, auth_status], _js="(url,msg)=>{ if(url && !url.startsWith('ERROR')) window.open(url,'_blank'); }")
|
| 507 |
finish_auth_btn.click(fn=finish_google_oauth, inputs=[code_input], outputs=[token_state, auth_status])
|
| 508 |
|
|
|
|
| 509 |
extract_btn.click(fn=handle_extract, inputs=[pdf_input], outputs=[assignments_state, classes_state, extract_status])
|
| 510 |
|
|
|
|
| 511 |
upload_assign_btn.click(fn=lambda f: upload_csv_to_df(f), inputs=[upload_assignments], outputs=[assignments_uploaded_state, upload_assign_status])
|
| 512 |
upload_classes_btn.click(fn=lambda f: upload_csv_to_df(f), inputs=[upload_classes], outputs=[classes_uploaded_state, upload_classes_status])
|
| 513 |
|
|
|
|
|
|
|
| 514 |
def preview_df(df):
|
| 515 |
if df is None:
|
| 516 |
return pd.DataFrame()
|
| 517 |
return df
|
| 518 |
|
| 519 |
+
upload_assign_btn.click(fn=lambda df: preview_df(df), inputs=[assignments_uploaded_state], outputs=[preview_uploaded_assignments])
|
| 520 |
+
upload_classes_btn.click(fn=lambda df: preview_df(df), inputs=[classes_uploaded_state], outputs=[preview_uploaded_classes])
|
|
|
|
|
|
|
| 521 |
|
|
|
|
| 522 |
send_extracted_assignments_btn.click(fn=send_extracted_assignments_to_calendar, inputs=[assignments_state, token_state], outputs=[send_extracted_assignments_status])
|
| 523 |
send_extracted_classes_btn.click(fn=send_extracted_classes_to_calendar, inputs=[classes_state, token_state], outputs=[send_extracted_classes_status])
|
| 524 |
|
| 525 |
send_uploaded_assignments_btn.click(fn=send_uploaded_assignments_to_calendar, inputs=[assignments_uploaded_state, token_state], outputs=[send_uploaded_assignments_status])
|
| 526 |
send_uploaded_classes_btn.click(fn=send_uploaded_classes_to_calendar, inputs=[classes_uploaded_state, token_state], outputs=[send_uploaded_classes_status])
|
| 527 |
|
| 528 |
+
gr.Markdown("### Notes\n- Click **Sign in with Google** then approve access. If your browser opens a new tab, the callback will save the authorization code. If not, copy the `code` param from the callback URL and paste it into the box and click **Finish Login**.\n- Ensure GoogleClientID, GoogleClientSecret, and REDIRECT_URI are set in the Space secrets.")
|
| 529 |
+
|
| 530 |
+
# Mount Gradio app onto FastAPI
|
| 531 |
+
gr.mount_gradio_app(app, demo, path="/")
|
| 532 |
|
| 533 |
+
# Launch with uvicorn when run directly (useful for local dev)
|
| 534 |
if __name__ == "__main__":
|
| 535 |
+
import uvicorn
|
| 536 |
+
port = int(os.environ.get("PORT", 7860))
|
| 537 |
+
uvicorn.run(app, host="0.0.0.0", port=port)
|