Spaces:
Runtime error
Runtime error
| from fastapi import FastAPI, Request | |
| from fastapi.responses import RedirectResponse, HTMLResponse | |
| from google.oauth2.credentials import Credentials | |
| from fastapi.staticfiles import StaticFiles | |
| from google_manager.constants import SCOPES | |
| from pages.load_page import load_page | |
| import google_auth_oauthlib.flow | |
| from starlette.middleware.sessions import SessionMiddleware | |
| import gradio as gr | |
| from gpt_summary import Ui | |
| from utils import credentials_to_dict | |
| # Create an instance of the FastAPI app | |
| app = FastAPI() | |
| # Add Session middleware to the app | |
| app.add_middleware(SessionMiddleware, secret_key="mysecret") | |
| # Mount the static files directory | |
| app.mount("/assets", StaticFiles(directory="assets"), name="assets") | |
| async def home(request: Request): | |
| # Load the html content of the auth page | |
| html_content = load_page("./pages/auth_page.html") | |
| if "credentials" not in request.session: | |
| return HTMLResponse(content=html_content, status_code=200) | |
| else: | |
| return RedirectResponse("/gradio/?__theme=dark") | |
| # Define the endpoint for Google authentication | |
| async def authorize(request: Request): | |
| flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( | |
| "credentials.json", scopes=SCOPES | |
| ) | |
| # for dev | |
| # flow.redirect_uri = "http://127.0.0.1:8000/auth_callback" | |
| # for production | |
| flow.redirect_uri = ( | |
| request.url.scheme | |
| + "://" | |
| + request.url.hostname | |
| + (":" + str(request.url.port) if request.url.port else "") | |
| + app.url_path_for("auth_callback") | |
| ) | |
| authorization_url, state = flow.authorization_url( | |
| access_type="offline", | |
| include_granted_scopes="true", | |
| ) | |
| request.session["state"] = state | |
| return RedirectResponse(url=authorization_url) | |
| # Define the callback endpoint after successful authentication | |
| async def auth_callback(request: Request): | |
| state = request.session["state"] | |
| flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( | |
| "credentials.json", scopes=SCOPES, state=state | |
| ) | |
| # for dev | |
| # flow.redirect_uri = "http://127.0.0.1:8000/auth_callback" | |
| # for production | |
| flow.redirect_uri = ( | |
| request.url.scheme | |
| + "://" | |
| + request.url.hostname | |
| + (":" + str(request.url.port) if request.url.port else "") | |
| + app.url_path_for("auth_callback") | |
| ) | |
| # Use the authorization server's response to fetch the OAuth 2.0 tokens. | |
| authorization_response = str(request.url) | |
| flow.fetch_token(authorization_response=authorization_response) | |
| credentials = flow.credentials | |
| request.session["credentials"] = credentials_to_dict(credentials) | |
| return RedirectResponse("/gradio?__theme=dark") | |
| # Mount the Gradio UI | |
| app = gr.mount_gradio_app(app, Ui, path="/gradio") | |