Rakshitjan's picture
Update main.py
e4f9983 verified
from fastapi import FastAPI
import gspread
from google.oauth2.service_account import Credentials
from google.auth.exceptions import GoogleAuthError
import os
# Define the Academic and Non-Academic panic buttons
academic_panic_buttons = ["MISSED CLASSES", "BACKLOGS", "LACK OF MOTIVATION", "NOT UNDERSTANDING", "BAD MARKS"]
non_academic_panic_buttons = ["EMOTIONAL FACTORS", "PROCRASTINATE", "LOST INTEREST", "LACK OF FOCUS", "GOALS NOT ACHIEVED", "LACK OF DISCIPLINE"]
app = FastAPI()
# Function to fetch the credentials
def get_credentials_from_env():
service_account_info = {
"type": os.getenv("SERVICE_ACCOUNT_TYPE"),
"project_id": os.getenv("PROJECT_ID"),
"private_key_id": os.getenv("PRIVATE_KEY_ID"),
"private_key": os.getenv("PRIVATE_KEY").replace('\\n', '\n'),
"client_email": os.getenv("CLIENT_EMAIL"),
"client_id": os.getenv("CLIENT_ID"),
"auth_uri": os.getenv("AUTH_URI"),
"token_uri": os.getenv("TOKEN_URI"),
"auth_provider_x509_cert_url": os.getenv("AUTH_PROVIDER_X509_CERT_URL"),
"client_x509_cert_url": os.getenv("CLIENT_X509_CERT_URL"),
"universe_domain": os.getenv("UNIVERSE_DOMAIN")
}
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
creds = Credentials.from_service_account_info(service_account_info, scopes=scope)
return creds
# Main function to fetch the panic button occurrences
@app.get("/panic-button-occurances")
def get_panic_button_occurrences():
try:
# Set up credentials
creds = get_credentials_from_env()
client = gspread.authorize(creds)
# Open the Google Sheet
sheet = client.open_by_url('https://docs.google.com/spreadsheets/d/1nFZGkCvRV6qS-mhsORhX3dxI0JSge32_UwWgWKl3eyw/edit?gid=0#gid=0').worksheet('Sheet1')
# Get all values from the sheet
data = sheet.get_all_values()
# Initialize the lists with panic button names and 0 counts
academic_list = {button: 0 for button in academic_panic_buttons}
non_academic_list = {button: 0 for button in non_academic_panic_buttons}
# Iterate through all rows in the data
for row in data:
for panic_button in row:
# Stop when an empty column is encountered
if not panic_button:
break
# Check and update counts for academic and non-academic panic buttons
if panic_button in academic_list:
academic_list[panic_button] += 1
elif panic_button in non_academic_list:
non_academic_list[panic_button] += 1
return {
"academic": academic_list,
"non_academic": non_academic_list
}
except GoogleAuthError as e:
return {"error": f"Authentication error: {e}"}
except gspread.exceptions.SpreadsheetNotFound:
return {"error": "Spreadsheet not found. Please check the URL."}
except Exception as e:
return {"error": f"An error occurred: {e}"}